Populate ComboBox from Database query

后端 未结 1 960
既然无缘
既然无缘 2021-01-26 13:06

I see many of the answers to similar question where people are saying that in order to get the value of the item loaded in combobox you need to use

  combobox1.d         


        
相关标签:
1条回答
  • 2021-01-26 13:56

    Rather than populating the items collection, you can bind a DataTable to the control to be used as the Datasource. Then, you can tell it which element to display and which value to submit to you when there is a selection:

    Using con As New SqlConnection(sConnection)
        Using com As New SqlCommand("Select Id, Name FROM ....", con)
            con.Open()
    
            Dim dt As New DataTable()
            dt.Load(com.ExecuteReader)
            cbox1.Datasource = dt
            cbox.DisplayMember = "Name"
            cbox.ValueMember = "Id"
        End Using
    End Using
    

    "Name" and "Id" would be column names from the database table. The event you probably want to work with in this case would be the SelectedValueChanged and SelectedValue would hold the ID related to the item selected. This will be returned as Object so you may need to cast it back to whatever it is.

    You can also bind to List(Of T) collections in the same way. In that case, the SelectedItem could be the entire object. For instance, using a List(of Employee), SelectedItem would be the object for the Employee the user selected.

    0 讨论(0)
提交回复
热议问题