0

我有一些文本框(使用 VS2010) 我正在尝试根据某人从组合框中选择的项目来填充 SQL Server 数据库中的列中的值。起初我能够显示组合框中第一项的值,但现在调试时什么都没有显示。代码:

Private Sub loadfields(sender As System.Object, e As System.EventArgs) Handles client_selection_combobox.SelectedIndexChanged
    Using myconnection As New SqlConnection("connection string")
        Dim loadfields As String = "SELECT company FROM ClientFileDatabase WHERE ClientFileDatabase.File_Name=@company;"
        Dim loadfields_sqlcommand As New SqlCommand(loadfields, myconnection)
        loadfields_sqlcommand.Parameters.Add("@company", SqlDbType.NVarChar)
        loadfields_sqlcommand.Parameters("@company").Value = client_selection_combobox.SelectedIndex.ToString

        Dim loadfields_dataadapter As New SqlDataAdapter
        loadfields_dataadapter.SelectCommand = loadfields_sqlcommand

        Dim loadfields_dataset As DataSet = New DataSet()
        loadfields_dataadapter.Fill(loadfields_dataset, "ClientFileDatabase")
        Dim loadfields_dataview = New DataView(loadfields_dataset.Tables("ClientFileDatabase"))

        companyname_textbox.DataBindings.Clear()
        companyname_textbox.DataBindings.Add("Text", loadfields_dataview, "Company")
        taxid_textbox.DataBindings.Clear()
        taxid_textbox.DataBindings.Add("Text", loadfields_dataview, "TaxIDNumber")
        accountmanager_textbox.DataBindings.Clear()
        accountmanager_textbox.DataBindings.Add("Text", loadfields_dataview, "AccountManager")
        etc...
    End Using
End Sub

我也尝试使用 SelectedValueChanged 和 SelectionChangeCommitted 事件处理程序无济于事。还尝试在设置数据绑定后使用刷新,但没有帮助。欢迎任何建议,谢谢!

4

1 回答 1

0

I personally like to use datatables, I find them easier to work with. I'm sure you will have more code to check to make sure dt.rows.count > 0 before actually attempting to work with the data, but here is how I would do it.

Dim loadfields_dataadapter As New SqlDataAdapter
Dim dt As New DataTable
loadfields_dataadapter.Fill(dt)

companyname_textbox.text = dt.Rows(0).Item("Company")
taxid_textbox.text = dt.Rows(0).Item("TaxIDNumber")
accountmanager_textbox.text = dt.Rows(0).Item("AccountManager")

Also, keep in mind that NULL fields in the database can cause runtime errors, so you may have to check for those as well.

于 2013-08-22T17:13:14.273 回答