Move to a specified record in a datatable
Hi I can find the datarow I want like so
VB Code:
Dim pkey(0) As DataColumn
pkey(0) = ds.Tables("ContactsCom").Columns(0)
ds.Tables("ContactsCom").PrimaryKey = pkey
Dim foundRow As DataRow
Dim findTheseVals(0) As Object
findTheseVals(0) = 11
foundRow = ds.Tables("ContactsCom").Rows.Find(findTheseVals)
If Not (foundRow Is Nothing) Then
MsgBox(foundRow(1).ToString())
End If
A simple question but how do I move to that datarow in the datatable, so all the bound controls show the value I have just found.
eg ds.Tables("ContactsCom").Move(11)
Re: Move to a specified record in a datatable
Okay have this, but there must be a better way to skin the cat
VB Code:
While Me.BindingContext(ds, "ContactsCom.ContactID").Current() <> 11
Me.BindingContext(ds, "ContactsCom").Position += 1
End While
There must be a way to find the position of the record I want and then set it, rather than iterating through the records.
Re: Move to a specified record in a datatable
Re: Move to a specified record in a datatable
Sorry have had a look at the dataview class and can't see how it would help, sure I must be missing something.
Re: Move to a specified record in a datatable
Dim dv As DataView
dv = New DataView(ds.Tables(0))
dv.RowFilter = "FieldName = " & findTheseVals(0)
Then bind to the dataview.
Note that, if you make a change while bound to dataview, it won't be updated to the database.
Re: Move to a specified record in a datatable
You could also use .Find.
Re: Move to a specified record in a datatable
The problem I was having was finding values in a datatable instead of going to the database and running a query. So I finally figured it out from the above post buts heres a nicer version:
VB Code:
'Code to find a value in a datatable
Dim dv As DataView = New DataView(DataTable) 'Set the dataview to the table to search
Dim rowValue As Integer = Nothing 'The value found
'Filter the dataview
dv.RowFilter = "ColumnNameToSearch = " & ValueToFind
'Make sure a record was found
If dv.Count > 0 Then
'Get the value from the record found
rowValue = dv.Item(0).Row("ColumnNameToGetValueFrom")
MessageBox.Show("The value found is " & rowValue)
Else
MessageBox.Show("No records found!")
End If
'To select a current record and show the values on the binding control
Dim rowPosition As Integer = Nothing 'The position of the value in the datatable
'Get the row position in the datatable
rowPosition = BindingSource.Find("ColumnNameToSearch", ValueToFind)
'Make sure a row was fouind and select it
If rowPosition = -1 Then
MessageBox.Show("No records found!")
Else
BindingSource.Position = rowPosition
End If
Just remember when you want to find a text value with
dv.RowFilter = "ColumnNameToSearch = " & ValueToFind
the filter must look like this "ColumnName = 'Text' "
without the ' you will get a column doesn't exist error.