如何搜索DataTable的具体记录?

时间:2013-06-28 14:12:36

标签: vb.net winforms datatable datarow

您好,

我有一个包含10个文本字段和1个组合框的窗体。

当用户选择组合框中的记录时,我想在我的表格数据表变量中找到该记录(称为 dtBranches ),然后从数据行填充我的10个文本字段。

我试过了:

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

但无法让它编译......

请问这是正确的,最好的方法是什么?

感谢

菲利普

2 个答案:

答案 0 :(得分:8)

DataTable.Select返回一个DataRows数组。您需要声明一个数组来接收结果

Dim dr() As System.Data.DataRow

当然,您需要检查是否返回了行并解决了数组中的第一行

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 ...

答案 1 :(得分:1)

我会使用Linq-ToDataSet和强类型Field方法代替:

Dim matches = From row In dtBranches
              Let SortCode = row.Field(Of String)("SortCode")
              Where SortCode = mSortCode
If matches.Any() Then
    Dim row = matches.First()
    Me.txtBranch.Text = row.Field(Of String)("Branch")
    Me.txtBankName.Text = row.Field(Of String)("BankName")
    Me.txtBranchTitle.Text = row.Field(Of String)("BranchTitle")
    Me.txtReference.Text = row.Field(Of String)("Ref")
    Me.txtAddr1.Text = row.Field(Of String)("Address1")
    Me.txtAddr2.Text = row.Field(Of String)("Address2")
    Me.txtAddr3.Text = row.Field(Of String)("Address3")
    Me.txtPostCode.Text = row.Field(Of String)("PostCode")
    Me.txtTelNo.Text = row.Field(Of String)("TelephoneNumber")
    Me.txtTown.Text = row.Field(Of String)("Town")
Else
    MesageBox.Show("SortCode not found.")
End If

如果您想要不区分大小写,请将上面的Where替换为:

Where StringComparer.OrdinalIgnoreCase.Equals(SortCode, mSortCode)

顺便说一下,您要拨两次电话号码。