-
Feb 20th, 2024, 10:11 AM
#1
Thread Starter
Frenzied Member
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...
-
Feb 20th, 2024, 10:22 AM
#2
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
-
Feb 20th, 2024, 05:41 PM
#3
Thread Starter
Frenzied Member
Re: Populating a Combobox display/value of states from text file
 Originally Posted by jmcilhinney
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.
-
Feb 20th, 2024, 08:42 PM
#4
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.
-
Feb 21st, 2024, 03:31 AM
#5
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.
-
Feb 21st, 2024, 05:41 AM
#6
Re: Populating a Combobox display/value of states from text file
 Originally Posted by ChrisE
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.
-
Feb 21st, 2024, 05:44 PM
#7
Thread Starter
Frenzied Member
Re: Populating a Combobox display/value of states from text file
 Originally Posted by jmcilhinney
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?
-
Feb 21st, 2024, 06:03 PM
#8
Thread Starter
Frenzied Member
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...
-
Feb 22nd, 2024, 12:50 AM
#9
Re: Populating a Combobox display/value of states from text file
 Originally Posted by nbrege
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.
-
Feb 22nd, 2024, 08:10 PM
#10
Re: Populating a Combobox display/value of states from text file
 Originally Posted by nbrege
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?
-
Feb 22nd, 2024, 08:21 PM
#11
Re: Populating a Combobox display/value of states from text file
 Originally Posted by jmcilhinney
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
Last edited by jmcilhinney; Feb 23rd, 2024 at 12:35 AM.
-
Feb 23rd, 2024, 09:03 AM
#12
Thread Starter
Frenzied Member
Re: Populating a Combobox display/value of states from text file
 Originally Posted by jmcilhinney
...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.
-
Feb 23rd, 2024, 09:17 AM
#13
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
-
Feb 23rd, 2024, 10:00 AM
#14
Thread Starter
Frenzied Member
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...
-
Feb 23rd, 2024, 10:29 AM
#15
Re: Populating a Combobox display/value of states from text file
That's my point ... which one represents Red? Which one represents black?
-tg
-
Feb 23rd, 2024, 12:55 PM
#16
Thread Starter
Frenzied Member
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.
-
Feb 23rd, 2024, 01:19 PM
#17
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
-
Feb 23rd, 2024, 01:36 PM
#18
Thread Starter
Frenzied Member
Re: Populating a Combobox display/value of states from text file
 Originally Posted by dbasnett
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.
-
Feb 23rd, 2024, 01:41 PM
#19
Re: Populating a Combobox display/value of states from text file
[QUOTE=nbrege;5633771]
 Originally Posted by dbasnett
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.
-
Feb 23rd, 2024, 03:00 PM
#20
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
-
Feb 23rd, 2024, 10:05 PM
#21
Re: Populating a Combobox display/value of states from text file
 Originally Posted by nbrege
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|