how to search DataTable for specific record?

Our Man in Bananas picture Our Man in Bananas · Jun 28, 2013 · Viewed 54.4k times · Source

Hi,

I have a windows form with 10 text fields and 1 combobox.

When the user selects a record in the combo-box I want to find that record in my form datatable variable (called dtBranches) then populate my 10 textfields from the datarow.

I tried this:

Dim dr As System.Data.DataRow
If mSortCode > 0 Then
    dr = dtBranches.Select("SortCode='" & mSortCode & "'")
    Me.txtBranch.Text = dr("Branch").ToString()
    Me.txtBankName.Text = dr("BankName").ToString()
    Me.txtBranchTitle.Text = dr("BranchTitle").ToString()
    Me.txtReference.Text = dr("Ref").ToString
    Me.txtAddr1.Text = dr("Address1").ToString
    Me.txtAddr2.Text = dr("Address2").ToString
    Me.txtAddr3.Text = dr("Address3").ToString
    Me.txtPostCode.Text = dr("PostCode").ToString
    Me.txtTelNo.Text = dr("TelephoneNumber").ToString
    Me.txtTown.Text = dr("Town").ToString
    Me.txtTelNo.Text = dr("TelephoneNumber").ToString
end if

but can't get it to compile...

What's the correct and best way to do this please?

thanks

Philip

Answer

Steve picture Steve · Jun 28, 2013

DataTable.Select returns an array of DataRows. You need to declare an array to receive the result

Dim dr() As System.Data.DataRow

Of course then you need to check if you have rows returned and address the first row in the array

dr = dtBranches.Select("SortCode='" & mSortCode & "'")
If dr.Length > 0 Then
    Me.txtBranch.Text = dr(0)("Branch").ToString()
    Me.txtBankName.Text = dr(0)("BankName").ToString()
    ...... and so on ...