How to loop through MS Access table-column values pulled in a Combo box (VB .Net)

久未见 提交于 2019-12-25 17:47:03

问题


This is in continuation of a previously resolved query related to Access Database values in Combo box. The code below is working fine. i.e. it gets the data from an Access table column into the dropdown of a combo-box. What I want is how to assign those values against the Combobox.SelectedIndex? I added TagComboBox1.SelectedIndex = 0 but I want something that will automatically assign Index to the values populated in the combo-box dropdown. The source table is tag_data ' Key Column is tag_unique_id

I need it as I want to use the combobox.selectedindexchanged event to carry out further tasks. I played around but did not succeed.

Dim dt As New DataTable
Dim query As String = "select tag_unique_id from tag_data order by tag_unique_id"
Using connection As New OleDbConnection(strConnectionString)
    Using command As New OleDbCommand(query, connection)
        Using adapter As New OleDbDataAdapter(command)
            connection.Open()
            adapter.Fill(dt)
            connection.Close()
        End Using
    End Using
End Using
If dt.Rows.Count > 0 Then
    TagComboBox1.DataSource = dt
    TagComboBox1.ValueMember = "tag_unique_id"
    TagComboBox1.DisplayMember = "tag_unique_id"
    TagComboBox1.SelectedIndex = 0
End If

UPDATE: Below is the combobox.selectedindexchanged code. The index can be anything during working of project and hence instead of specifying as selectedindex=0 (1,2,3..) can I have a variable which will assign a new value to selectedindexchanged event?

 Private Sub TagComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As system.EventArgs) Handles TagComboBox1.SelectedIndexChanged
'reference http://stackoverflow.com/questions/13152534/view-data-from-database-using-textbox
Dim dt As New DataTable
Dim query As String = "select tag_text from tag_data"
Dim dr As OleDbDataReader
Dim connection As New OleDbConnection(strConnectionString)
Dim command As New OleDbCommand(query, connection)
connection.Open()
If TagComboBox1.SelectedIndex = 0 Then

    dr = command.ExecuteReader
    While dr.Read()
        TagTextBox.Text = dr("tag_text").ToString
    End While
    dr.Close()

End If

回答1:


If you are trying to populate a textbox according to the selected index of the combobox this is what you need to do.

For index As Integer = 0 To (ComboBox1.Items.Count - 1)
        textbox.Text = ComboBox1.Items(index)
    Next


来源:https://stackoverflow.com/questions/25061559/how-to-loop-through-ms-access-table-column-values-pulled-in-a-combo-box-vb-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!