我正在尝试用数据填充一堆控件。这些控件包括组合框、文本框、日期/时间等。
我最初让用户做出选择/输入数据并保存记录。对于组合框,我显示文本,但是,保存一个值,作为一个例子…
ValueMember DisplayMember
100 Accounting
101 Finance
在本例中,如果用户选择Accounting,我将其保存为100。
现在我正在尝试用正确的数据填充这些控件,并将选择设置为保存此记录时的值。
这就是我获取数据的方式…
dim querystring as string
dim count as integer
QueryString = "Select FirstName, LastName, Dept, Position from TblClients where IdClient = 1112"
Dim cmd As New SqlCommand(queryString, Conn)
Conn.Open()
Using sdA As New SqlDataAdapter
Using dtA As New DataTable
sdA.SelectCommand = cmd
count = sdA.Fill(dtA)
If count <> 0 Then
MsgBox("Success")
End If
cboContactCategory.SelectedValue = dtA.Rows(0)("Dept").ToString
End Using
End Using
Conn.Close()
FirstName = txtFirst;LastName = txtLast, Position = cbposition, Dept = cboDept
我该如何设置这些值?
给定查询,您将几个字段加载到DataTable
中,然后在DataTable
被处置之前不检索数据:
txtFirst.Text = dtA.Rows(0).Item("FirstName")
txtLast.Text = dtA.Rows(0).Item("LastName")
如果您保留DataTable
,您可能需要使用数据绑定:
txtFirst.DataBindings.Add("Text", dtClients, "FirstName")
txtLast.DataBindings.Add("Text", dtClients, "LastName")
当前行的值将显示在这些控件中。
如果您持久化DataTable
并将所有客户端加载到其中,则不必运行查询来查找某人:
dtClients.DefaultView.RowFilter = String.Format("ID = {0}", intIdToFind)
' text filter:
dtClients.DefaultView.RowFilter = String.Format("Country = '{0}'", "Belgium")
这将视图过滤到一个客户端,或者根据需要过滤到比利时的所有客户端。无需编写更多的SQL或查询数据库。当然,如果有成千上万的客户,您可能希望一次加载一个子集-那些在比利时的客户,那些在过去60天内订购的客户或其他客户。
一个完全配置的DataAdapter
也可以为你执行所有的更新,删除。在某些情况下,每个表可能只需要一条SQL语句。查看通过datagridview搜索值的示例