我设法将数据从SQL表中的列添加到ComboBox中,但是我需要将所有行都显示在其余的文本框中。 (我希望我的措词正确)。
这是我当前的代码:
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SqlConnection("Data Source=xxxx;Initial Catalog=ltLeavers;Integrated Security=True")
Dim da As New SqlDataAdapter("SELECT * FROM dbo.mytable", con)
Dim dt As New DataTable
da.Fill(dt)
ComboBox1.DisplayMember = "DISPLAY_NAME"
ComboBox1.DataSource = dt
End Sub
上面的方法没有问题,所有项目都添加到ComboBox中,但是我需要另外两列EMAIL_ADDRESS和DEPARTMENT的相应行从ComboBox中选择的内容添加到TextBoxes中。
答案 0 :(得分:2)
在ComboBox的SelectedIndex_Changed
事件下;输入以下代码。
Dim dt As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SqlConnection("Data Source=xxxx;Initial Catalog=ltLeavers;Integrated Security=True")
Dim da As New SqlDataAdapter("SELECT * FROM dbo.mytable", con)
da.Fill(dt)
ComboBox1.DisplayMember = "DISPLAY_NAME"
ComboBox1.DataSource = dt
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Textbox1.Text = CStr(dt.Rows(ComboBox1.SelectedIndex)("EMAIL_ADDRESS"))
Textbox2.Text = CStr(dt.Rows(ComboBox1.SelectedIndex)("DEPARTMENT"))
End Sub
您将需要在表单的load事件之外声明数据表dt,以便组合框的SelectedIndex_Changed事件可以看到它。
答案 1 :(得分:0)
我建议您使用BindingSource
完成它。
尝试一下:
1-声明带有事件的变量类型BindingSource
。另外,声明您的数据集将用于数据。
Dim WithEvents BS As New BindingSource
Dim ds As New DataSet
2-在您的Form
Load
事件中,查询您的数据并将其与Binding Source和ComboBox
控件进行绑定。
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SqlConnection("Data Source=xxxx;Initial Catalog=ltLeavers;Integrated Security=True")
Dim da As New SqlDataAdapter("SELECT * FROM dbo.mytable", con)
da.Fill(ds, "myPopulatedTable")
ComboBox1.DisplayMember = "id"
ComboBox1.DataSource = ds.Tables("myPopulatedTable")
'Here the new code'
BS.DataSource = ds
BS.DataMember = "myPopulatedTable"
End Sub
3-添加一个Sub Procedure
,以将数据显示到其他文本框控件中。
Private Sub DISPLAYRECORD(Optional ByVal table As String = "myPopulatedTable")
TextBox1.Text = ds.Tables(table).Rows(Me.BS.Position)("column1").ToString
TextBox2.Text = ds.Tables(table).Rows(Me.BS.Position)("column2").ToString()
TextBox2.Text = ds.Tables(table).Rows(Me.BS.Position)("column3").ToString()
End Sub
4-在绑定源的PositionChanged
事件中,调用该子过程(上述)
Private Sub BS_PositionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles BS.PositionChanged
DISPLAYRECORD()
End Sub
5-最后,要将数据与ComboBox
选择同步,您需要根据ComboBox
索引选择更改该绑定源的位置
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
BS.Position = ComboBox1.SelectedIndex
End Sub