DataTable and Row Numbers

  • Thread starter Thread starter Jason Callas
  • Start date Start date
J

Jason Callas

I have a datatable. I know I can call the method dt.Item(n) to get nth row.
What I need to do is, given a DataRow object, retrieve the row number. Look
at the sample code.

Dim dt As New DataTable
dt.Columns.Add(New DataColumn("symbol"))

Dim row As DataRow

row = dt.NewRow
row("symbol") = "MSFT"
dt.Rows.Add(row)

row = dt.NewRow
row("symbol") = "AAPL"
dt.Rows.Add(row)

For Each row In dt.Rows
Debug.WriteLine("The symbol " & row.Item("symbol").ToString() & " is
row...")
Next

Thanks,
Jason
 
I don't think there are any methods/properties that return the index of a
DataRow in a DataRowCollection (someone correct me if I'm wrong). If this
functionality is really important, you can always write your own method to
return the index. One simple way is to enumerate through the collection,
and whenever you find your datarow, return that index.

Another, more elegant, way to give each row in your table an index is to
create a new column in your table that could be the "id" column with type
Int32 and AutoIncrement property set to true. This will give you an identity
column which you could use to retrieve the "index" of the row in the table.

Eric
 
I thought about doing that but I do not like it.

There has to be SOME way. If I bind a table to a grid and I update a column
in the table, the correct cell on the grid gets refreshed. Same thing
happens if I update a cell on the grid, the correct row and column in the
table is set. Somewhere there is a link or mapping....
 
Back
Top