0

My code is:

Private Function CreateID() As Integer
    'finds the current highest ID
    For Each row As DataRow In MedDT.Rows
        If row.Item("MedicineID") > CreateID Then
            CreateID = row.Item("MedicineID")
        End If
    Next
    'returns a value for eventID that is unused as its higher then the current highest
    Return CreateID
End Function

It should automatically generate a number which is one higher than the highest value in the DataTable but for some reason it isn't working I call the procedure in the Form_Load procedure to fill a text box.

AMIC MING
  • 6,306
  • 6
  • 46
  • 62
  • 1
    You can avoid this function altogether by declaring your column auto-generated (IDENTITY on SQL Server). Just my 2 cents – Machinarius Apr 01 '14 at 01:23
  • Thanks but I'm trying to get this working for now, may look at different ways at a later date. It works fine on another form I have, just not this one. – FailedWolfhound Apr 01 '14 at 01:29

2 Answers2

0

You are scanning a DataSet for the highest MedicineID number but you forgot to increment that value by 1 before returning, just change your return statement to:

Return CreateID + 1

You should just mark the ID column as IDENTITY and forget about that trivial thing though

Machinarius
  • 3,637
  • 3
  • 30
  • 53
  • I have just added your suggested change `Return CreateID + 1` and it still doesn't work unfortunately – FailedWolfhound Apr 01 '14 at 01:30
  • Thanks for the suggestion, although I haven't taken any heed, I'm grateful. Will try your suggestions at a later date. Found the problem and it is in the code where I fill my DataTable. I was SELECTing the wrong data from the DataBase. – FailedWolfhound Apr 01 '14 at 01:36
  • The problem might lie in the fact that DataRow.Item[String] (http://msdn.microsoft.com/en-us/library/146h6tk5.aspx)returns an Object and the implicit cast could be distorting the data in some way. Not to mention CreateID could be of a non-integer type, also casted implicitly to integer on return. Add the type of CreateID to the example code – Machinarius Apr 01 '14 at 01:37
  • Good to know your problem is solved, may you not find yourself in a situation like this again. – Machinarius Apr 01 '14 at 01:38
0

Just to add to what Machinarius has said, Data Table itself has an auto Increment option on a column

DataColumn.AutoIncrement = true;
DataColumn.AutoIncrementSeed = 1;
DataColumn.AutoIncrementStep = 1;

so if you are not loading the data from a database you could also use this option.

David Molyneux
  • 304
  • 2
  • 12