Results 1 to 21 of 21

Thread: Populating a Combobox display/value of states from text file

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Jul 2006
    Location
    MI
    Posts
    1,975

    Populating a Combobox display/value of states from text file

    If I have a text file with all the state names & 2-letter abbreviations, how do I read that in to a Combobox & set the Display member & Value member? I want the Combo to show the full state name, but get the 2-letter abbreviation for it when selected. Thanks...

    Text file format is as follows:

    Code:
    Alabama,AL
    Alaska,AK
    Arizona,AZ
    Arkansas,AR
    etc...

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,478

    Re: Populating a Combobox display/value of states from text file

    You need to read each line into an instance of a type that has two properties - one for each value. You can then bind a list of those objects to the ComboBox and specify one property name as the DisplayMember and the other as the ValueMember. You can define your own type or you can just use Tuples, e.g.
    Code:
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim states = (From line In File.ReadLines("file path here")
                      Let parts = line.Split(","c)
                      Select Tuple.Create(parts(0), parts(1))).ToArray()
    
        With ComboBox1
            .DisplayMember = "Item1"
            .ValueMember = "Item2"
            .DataSource = states
        End With
    End Sub

  3. #3

    Thread Starter
    Frenzied Member
    Join Date
    Jul 2006
    Location
    MI
    Posts
    1,975

    Re: Populating a Combobox display/value of states from text file

    Quote Originally Posted by jmcilhinney View Post
    You need to read each line into an instance of a type that has two properties - one for each value. You can then bind a list of those objects to the ComboBox and specify one property name as the DisplayMember and the other as the ValueMember. You can define your own type or you can just use Tuples, e.g.
    JMC, thank you. This method works fine except I found that if the Combobox.Sorted property is set to True, then it doesn't display the items properly. It displays both values enclosed in brackets. So for example it will show [Alabama,AL]. So it works great if the items in the text file are already in the order you want them displayed, but if they are not in order & you set the Sorted property to true it does not work. Do you know why that is & what the fix would be? Would you have to sort the datasource first before assigning to the control?
    Last edited by jmcilhinney; Feb 21st, 2024 at 05:42 AM.

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,478

    Re: Populating a Combobox display/value of states from text file

    When the Sorted property is True, it seems not to be honouring the DisplayMember based on that code. It seems to be displaying the result of calling ToString on each item rather than using the DisplayMember. I just tested with a custom type instead of a Tuple and got the type name in the control, which would be what you'd see if you hadn't set the DisplayMember. As a rule, you should always set the DataSource after the DisplayMember and ValueMember. There are often exceptions to rules though, and this is one such exception. If you set the DataSource first and then the DisplayMember and ValueMember, the data is displayed correctly. That goes for Tuples and custom types.

  5. #5
    PowerPoster ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    3,066

    Re: Populating a Combobox display/value of states from text file

    you could use OLEDB, but that might be an overkill, I like JMC's sample

    here the OLEDB sample, the CharacterSet 65001 is for Germany, you can Sort with ASC or DESC
    Code:
     Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
            ProcessFileStates("E:\TestFolder\States.txt")
        End Sub
    
        Public Sub ProcessFileStates(ByVal filename As String)
            Dim file As New FileInfo(filename)
    
            Using con As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=""" & file.DirectoryName & """; Extended Properties='text;HDR=NO;FMT=Delimited(,);CharacterSet=65001';")
                'CharacterSet 65001 is for German Umlaute  ?", "?", "?", "?", "?", "?
                Using cmd As New OleDbCommand(String.Format("SELECT F1 As State,F2 as S FROM [{0}] ORDER BY F1 ASC;", file.Name), con)
                    cmd.CommandType = CommandType.Text
                    Using sda As New OleDbDataAdapter(cmd)
                        Using ds As New DataSet()
                            sda.Fill(ds)
                            'DataGridView1.DataSource = ds.Tables(0)
    
                            With ComboBox1
                                .DisplayMember = "State"
                                .ValueMember = "S"
                                .DataSource = ds.Tables(0)
                            End With
                        End Using
                    End Using
                End Using
            End Using
        End Sub
    
        Private Sub ComboBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
            Label1.Text = ComboBox1.SelectedValue
        End Sub
    somehow I could not Rate JMC's Post#2
    also the German Umlaute show as ?
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  6. #6
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,478

    Re: Populating a Combobox display/value of states from text file

    Quote Originally Posted by ChrisE View Post
    somehow I could not Rate JMC's Post#2
    also the German Umlaute show as ?
    The site is having some issues at the moment. I had the same problem with an accented character the other day and suspect that that has the same root cause. The Reply With Quote button isn't working properly so I'd not be surprised if the same issue is affecting repping posts.

  7. #7

    Thread Starter
    Frenzied Member
    Join Date
    Jul 2006
    Location
    MI
    Posts
    1,975

    Re: Populating a Combobox display/value of states from text file

    Quote Originally Posted by jmcilhinney View Post
    When the Sorted property is True, it seems not to be honouring the DisplayMember based on that code. It seems to be displaying the result of calling ToString on each item rather than using the DisplayMember. I just tested with a custom type instead of a Tuple and got the type name in the control, which would be what you'd see if you hadn't set the DisplayMember. As a rule, you should always set the DataSource after the DisplayMember and ValueMember. There are often exceptions to rules though, and this is one such exception. If you set the DataSource first and then the DisplayMember and ValueMember, the data is displayed correctly. That goes for Tuples and custom types.
    Thanks, that works. I would think that sorting the datasource first would also work, but I haven't tried that. Is there any way to do that with the code you posted in #2?

  8. #8

    Thread Starter
    Frenzied Member
    Join Date
    Jul 2006
    Location
    MI
    Posts
    1,975

    Re: Populating a Combobox display/value of states from text file

    It looks like I spoke too soon. When sorted is True it only sorts the Display member. The Value member doesn't follow, so they become disassociated. It looks like I'm back to figuring out how to sort the datasource first...

  9. #9
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,478

    Re: Populating a Combobox display/value of states from text file

    Quote Originally Posted by nbrege View Post
    Thanks, that works. I would think that sorting the datasource first would also work, but I haven't tried that. Is there any way to do that with the code you posted in #2?
    An Order By clause in the LINQ query would do it. I'll provide updated code.

  10. #10
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,478

    Re: Populating a Combobox display/value of states from text file

    Quote Originally Posted by nbrege View Post
    It looks like I spoke too soon. When sorted is True it only sorts the Display member. The Value member doesn't follow, so they become disassociated. It looks like I'm back to figuring out how to sort the datasource first...
    I would have posted sooner but the site seems to have been having issues.

    I would think that you should just be able to get the SelectedValue and it should work, regardless of sorting. Can you provide the specific code that is not working as expected?

  11. #11
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,478

    Re: Populating a Combobox display/value of states from text file

    Quote Originally Posted by jmcilhinney View Post
    An Order By clause in the LINQ query would do it. I'll provide updated code.
    Here is the original code with an appropriate Order By clause added:
    Code:
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim states = (From line In File.ReadLines("file path here")
                      Let parts = line.Split(","c)
                      Order By parts(0)
                      Select Tuple.Create(parts(0), parts(1))).ToArray()
    
        With ComboBox1
            .DisplayMember = "Item1"
            .ValueMember = "Item2"
            .DataSource = states
        End With
    End Sub
    You could also use an anonymous type to populated the list, as long as you didn't need to cast an item as its actual type later:
    Code:
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim states = (From line In File.ReadLines("file path here")
                      Let parts = line.Split(","c)
                      Order By parts(0)
                      Select New With {.Name = parts(0), .Code = parts(1)}).ToArray()
    
        With ComboBox1
            .DataSource = states
            .DisplayMember = "Name"
            .ValueMember = "Code"
        End With
    End Sub

  12. #12

    Thread Starter
    Frenzied Member
    Join Date
    Jul 2006
    Location
    MI
    Posts
    1,975

    Re: Populating a Combobox display/value of states from text file

    Quote Originally Posted by jmcilhinney View Post
    ...Can you provide the specific code that is not working as expected?
    Here is the exact code I'm using for testing:

    Code:
        Dim myFile As String = "D:\Temp\ComboTest.txt"
    
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    
            Dim lines As String() = File.ReadAllLines(myFile, System.Text.Encoding.ASCII)
            Dim items As New List(Of KeyValuePair(Of String, String))()
    
            For Each line As String In lines
    
                If line.Split(","c).Count = 1 Then
                    items.Add(New KeyValuePair(Of String, String)(line, "None"))
                ElseIf line.Split(","c).Count > 1 Then
                    items.Add(New KeyValuePair(Of String, String)(line.Split(","c)(0), line.Split(","c)(1)))
                End If
    
            Next
    
            Me.ComboBox2.DataSource = items
            Me.ComboBox2.DisplayMember = "Key"
            Me.ComboBox2.ValueMember = "Value"
            'Me.ComboBox2.SelectedIndex = -1
    
        End Sub
    
    
        Private Sub ComboBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox2.SelectedIndexChanged
    
            Dim selVal As String = Me.ComboBox2.SelectedValue.ToString
            Me.TextBox2.Text = selVal
    
        End Sub
    And here is the contents of the file I'm using for testing:

    Code:
    Red
    Green,W
    Blue
    Yellow,X
    Orange
    Purple,Y
    Black
    White,Z
    As you can see, the items aren't in alphabetical order & some lines have 1 item & some have 2 items, separated by a comma, hence the IfThenElse statement that adds "None" for the Value in the items list for the lines with only 1 item. ComboBox2.Sorted property is set to True. When I click Button2, the Combobox is loaded & the Display members are in the correct order & when I select an item it should show the Value member in TextBox2, which it does, but it doesn't show the correct value that's in the text file. So for example, when I select Yellow from the dropdown menu, it should show "X" in the textbox, but instead it shows "Z" and if I select Blue it should show "None", but it shows "W".

    Also, I'd like the combobox to not display any item when first loaded, so I tried setting the SelectedIndex to -1, but then that throws an error in the SelectedIndexChanged event. Any ideas on how to get this to work the way I want?
    Last edited by nbrege; Feb 23rd, 2024 at 09:09 AM.

  13. #13
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,569

    Re: Populating a Combobox display/value of states from text file

    Use hte System.SortedClass ... it'll sort entries based on the key.

    Thing is though... you're going to end up with a bunch of "None" values in the list ... which one is Red? Which one is Black? Or Blue?


    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  14. #14

    Thread Starter
    Frenzied Member
    Join Date
    Jul 2006
    Location
    MI
    Posts
    1,975

    Re: Populating a Combobox display/value of states from text file

    There should only be "None" where there's only 1 item per line in the file. So In my test example above, there should be 4 "None"s...

  15. #15
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,569

    Re: Populating a Combobox display/value of states from text file

    That's my point ... which one represents Red? Which one represents black?


    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  16. #16

    Thread Starter
    Frenzied Member
    Join Date
    Jul 2006
    Location
    MI
    Posts
    1,975

    Re: Populating a Combobox display/value of states from text file

    I found a solution that works exactly how I want, using a SortedList, which I didn't know existed until today.
    I just had to handle the error I was getting when setting the SelectedIndex to -1, which I did in the SelectedIndexChanged event.
    The ComboBox.Sorted property is now set to False. The line items populate the ComboBox in alphabetical order & the Value members are associated properly.


    Here is my code:

    Code:
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    
            Dim lines As String() = IO.File.ReadAllLines(myFile, System.Text.Encoding.ASCII)
            Dim mySL As SortedList(Of String, String) = New SortedList(Of String, String)()
    
            For Each line As String In lines
    
                If line.Split(","c).Count = 1 Then
                    mySL.Add(line, "None")
                ElseIf line.Split(","c).Count > 1 Then
                    mySL.Add(line.Split(","c)(0), line.Split(","c)(1))
                End If
    
            Next
    
            Me.ComboBox2.DataSource = mySL.ToList
            Me.ComboBox2.DisplayMember = "Key"
            Me.ComboBox2.ValueMember = "Value"
            Me.ComboBox2.SelectedIndex = -1
    
        End Sub
    
        Private Sub ComboBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox2.SelectedIndexChanged
    
            If Me.ComboBox2.SelectedValue Is Nothing Then
                Me.TextBox2.ResetText()
            Else
                Me.TextBox2.Text = Me.ComboBox2.SelectedValue.ToString
            End If
    
        End Sub
    Last edited by nbrege; Feb 23rd, 2024 at 12:59 PM.

  17. #17
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,776

    Re: Populating a Combobox display/value of states from text file

    The kludgey way

    Code:
        Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
            Dim lns() As String = My.Resources.StatesAndCapitals.Split({ControlChars.Cr})
            Dim STabbrev As New SortedDictionary(Of String, String)
    
            For Each rw As String In lns
                Dim parts() As String = rw.Split(","c) 'state abbrev. capital
                STabbrev.Add(parts(0), parts(1))
            Next
    
            With ComboBox1
                .DataSource = New BindingSource(STabbrev, Nothing)
                .DisplayMember = "Key"
                .ValueMember = "Value"
            End With
        End Sub
    
        Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
            Debug.Write(ComboBox1.Text) 'DisplayMember
            Debug.Write(ControlChars.Tab)
            Debug.WriteLine(ComboBox1.SelectedValue) 'ValueMember
        End Sub
    ATTACHED file used.StatesAndCapitals.txt
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  18. #18

    Thread Starter
    Frenzied Member
    Join Date
    Jul 2006
    Location
    MI
    Posts
    1,975

    Re: Populating a Combobox display/value of states from text file

    Quote Originally Posted by dbasnett View Post
    The kludgey way

    I'm sure that no matter how you choose to do this, it will be kludgey. I was also not aware of SortedDictionary. Does that offer any benefit over a SortedList?
    Last edited by nbrege; Feb 23rd, 2024 at 01:52 PM.

  19. #19
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,776

    Re: Populating a Combobox display/value of states from text file

    [QUOTE=nbrege;5633771]
    Quote Originally Posted by dbasnett View Post
    The kludgey way


    I'm sure that no matter how you choose to do this, it will be kludgey. I was also not aware of SortedDictionary. Does that offer any benefit over a SortedList?
    For this probably not, not sure if there is even a difference.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  20. #20
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,569

    Re: Populating a Combobox display/value of states from text file

    In this case, likely not... SortedDictionary sorts on the key ... SortedList on the other hand will sort by default on the first item... The other difference is that you can also hand the SortedList a custom comparator for cases where you're storing a complex object in the list ... Not sure SortedDictionary allows for that but I haven't had a chance to look or try it out... Might do that sometime tonight if I remember.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  21. #21
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,478

    Re: Populating a Combobox display/value of states from text file

    Quote Originally Posted by nbrege View Post
    I was also not aware of SortedDictionary. Does that offer any benefit over a SortedList?
    That's like asking whether a List is better than a Dictionary. They both work for scenarios that they work in. If you need a simple list that is sorted then you use a SortedList. If you need a keyed collection sorted by key then you use a SortedDictionary. It's not that one is better than the other. They each work in appropriate situations. Either you need keys or you don't, so that is what will make the decision for you.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width