SQL 列到文本框(来自组合框)

SQL Column to TextBox (from ComboBox)

我已经设法从我的 SQL table 的列中将数据添加到 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 以从中选择的内容添加到 TextBoxes 中组合框。

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

您需要在表单的加载事件之外声明数据 table dt,以便组合框的 SelectedIndex_Changed 事件可以看到它。

我建议你使用 BindingSource 来完成它。

试试这个:

1- 使用事件声明 BindingSource 的变量类型。另外,声明您的数据集将用于数据。

Dim WithEvents BS As New BindingSource
Dim ds As New DataSet

2- 在您的 Form Load 事件中,查询您的数据并将其与绑定源和您的 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- 在 Binding Source 的 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