Binding Data from a Text File to a Combo Box

Benemin

Member
Joined
Feb 17, 2010
Messages
12
Location
England
Programming Experience
Beginner
This is the contents of the text file:

9,1,First Street
9,2,Second Street
9,3,Third Street
9,4,Fourth Street

I have a combo box on a form and I want to bind some of the data from the text file, the stuff highlighted in bold, to the combo box. How would I go about doing this?
 
There are many ways to do that.

You can simply iterate over each record in the Text File and add the needed data to a List. Then bind that List to the ComboBox.

Or

You can read the TextFile in as a DataTable, then bind that DataTable to the ComboBox.
 
I would say enter this data into a datatable and then bind it to a combobox property, i.e. Display Member.
 
I'm assuming you want the description to be what's shown in the combobox and the number to be the value associated with it.

Here's a quick example of what rcombs4 and daniness were talking about.

VB.NET:
        Dim ds As New DataSet
        Dim dt As New DataTable

        With dt.Columns
            .Add("Column1", GetType(Integer))
            .Add("Column2", GetType(Integer))
            .Add("Column3", GetType(String))
        End With

        For Each line In IO.File.ReadAllLines("C:\Temp\cboValues.txt")
            dt.Rows.Add(line.Split(","c))
        Next

        With ComboBox1
            .DataSource = dt
            .DisplayMember = "Column3"
            .ValueMember = "Column2"
            .SelectedIndex = 0
        End With
 
i found that reading if you read the data from a text file and enter the required data into a string array it actually becomes quite easy . you just need to specify which position of the array you need to display


VB.NET:
 If File.Exists(textfile) Then

            Dim read As New StreamReader(textfile)

            Dim temp As String
            Dim data As String()
            Try

                While read.Peek <> -1

                    temp = read.ReadLine()

                    data = temp.Split(",")
                    combobox1.Items.Add(data(0))

                End While
 
Back
Top