使用表字段填充Combobox并用于插入新记录

时间:2014-02-27 18:50:32

标签: sql-server vb.net winforms combobox

我通过WinForms将新员工输入数据库。

我的Company表看起来像:

+----------+--------------+
| CMPNY_ID |   CMPNY_NM   |
+----------+--------------+
|    01    |      ABC     |
+----------+--------------+
|    02    |      DEF     |
+----------+--------------+

我想填充一个Combobox,以便用户看到CMPNY_NM - > “ABC”。 当用户输入新员工时,他们可以选择公司名称。 与他们选择的CMPNY_ID相关联的CMPNY_NM会添加到员工的记录中。

如果您输入新记录,则应输入员工名字,姓氏,然后从组合框ABC中选择。那将保持与ABC相关的PK - > “01”并将与其余信息一起插入数据库。数据看起来像:

+----------+--------------+------------+
|  EMP_ID  |    EMP_NM    |  CMPNY_ID  |
+----------+--------------+------------+
|    01    |      ABC     |     01     |
+----------+--------------+------------+

我没有太多,但到目前为止我有:

    Dim ds As New DataSet()
    Dim conn As New SqlConnection("Data Source=SQLTEST_HR,4000\SQLEXPRESS;Integrated Security=True")

    Dim qry As String

    qry &= "SELECT CMPNY_SEQ_ID, CMPNY_NM"
    qry &= "FROM CMPNY"

    conn.Open()
    Using da As New SqlDataAdapter(qry, conn)
        da.Fill(ds, "CMPNY")
    End Using

    With PaymentCbx
        .DisplayMember = "CMPNY_NM"
        .DataSource = ds.Tables("CMPNY")
        .SelectedIndex = 0
    End With

    MyBase.OnLoad(e)

这似乎没有做任何事,真的。

欢迎任何帮助。

2 个答案:

答案 0 :(得分:2)

试试这个 ON FORM LOAD

    Dim ds As New DataSet()
    Dim conn As New SqlConnection("YOUR CONNECTION STRING")

    Dim qry As String = ""

    qry &= "SELECT CMPNY_ID, CMPNY_NM "
    qry &= " FROM CMPNY"

    conn.Open()
    Using da As New SqlDataAdapter(qry, conn)
        da.Fill(ds, "CMPNY")
    End Using

    PaymentCbx.DataSource = ds.Tables("CMPNY")
    PaymentCbx.DisplayMember = "CMPNY_NM"
    PaymentCbx.ValueMember = "CMPNY_ID"
    PaymentCbx.SelectedIndex = 0

并在Combobox SelectedValueChanged事件中编写代码

 Dim companyid As String = PaymentCbx.SelectedValue.ToString

答案 1 :(得分:1)

我认为你只是错过了组合框的ValueMember。 DisplayMember设置组合框中显示的内容,ValueMember选择显示的值所代表的值。

Dim dt As New DataTable()
Dim conn As New SqlConnection("Data Source=SQLTEST_HR,4000\SQLEXPRESS;Integrated Security=True")

Dim qry As String = "SELECT CMPNY_SEQ_ID, CMPNY_NM FROM CMPNY"

conn.Open()
Using da As New SqlDataAdapter(qry, conn)
    da.Fill(dt)
End Using

With PaymentCbx
    .DisplayMember = "CMPNY_NM"
    .ValueMember = "CMPNY_SEQ_ID"
    .DataSource = dt
    .SelectedIndex = 0
End With

MyBase.OnLoad(e)

在按钮单击事件中,一旦用户填写了剩余的信息,您就可以使用组合框的.SelectedValue属性来获取值。

Dim companyId as Integer = PaymentCbx.SelectedValue

希望有所帮助。