You're close on your second try -- replace SelectedItem with SelectedIndex:
cboCountry.SelectedIndex = cboCountry.FindString(row.Item("CCCOUNTRY").ToString)
Question
I've been looking around for this answer. Checked here: How to set a combobox value but I'm not sure if it applies to me (could be wrong, please correct me if I am). I'm using VB.Net, VS2012 and I need to programmatically set the value member of a combobox that is databound.
My code now is as follows (this is from within a loop assigning a bunch of controls values):
cboCountry.SelectedValue = row.Item("CCCOUNTRY").ToString
This does not assign any selected value. I have also tried:
cboCountry.SelectedItem = cboCountry.FindString(row.Item("CCCOUNTRY").ToString)
But this does not work either. For this instance:
Again, all I need to do is set the selectedvalue programmatically. Any help greatly appreciated!
Solution
You're close on your second try -- replace SelectedItem with SelectedIndex:
cboCountry.SelectedIndex = cboCountry.FindString(row.Item("CCCOUNTRY").ToString)
OTHER TIPS
You should use:
cboCountry.Items.FindByText(row.Item("CCCOUNTRY").ToString()).Selected = True
This worked for me today in vb.net vs2010
cboCountry.SelectedIndex = cboCountry.FindString("CCCOUNTRY").ToString
The names of the controls and values for me were different, but I continued the previous users posts...
This worked for me in a project with VB.NET VS2010
cboCountry.SelectedIndex = cboCountry.FindString("CCCOUNTRY").ToString
of course the project has different names and values
I have been experiencing the same problem and have not found an answer on the net. Apparently, Microsoft has not fixed this problem yet. I am using VB for a VS2010 WinForms app (in Windows 7). I finally decided to code a work around, Wherever I was trying to preset the selected value of a ComboBox I made the following change:
' my_cbx.SelectedValue = data_row.value ' doesn't work!
PresetSelectedValue(my_cbx, data_row.value)
Then, I added the following subroutine to be called by the above changes:
Public Sub PresetSelectedValue(ByRef ComboBox As ComboBox, ByVal value As Object)
Dim item_ndx As Integer
If ComboBox Is Nothing Then
' throw exception?
Exit Sub
End If
With ComboBox
.Tag = "PresetSelectedValue"
For item_ndx = 0 To .Items.Count - 1
.SelectedIndex = item_ndx
If .SelectedValue = value Then
Exit For
End If
Next
If item_ndx >= .Items.Count Then
.SelectedIndex = -1
End If
.Tag = ""
End With
End Sub
Finally, I added the following code to my ComboBox.SelectedValueChanged event (this prevents the normal event logic when user changes the value from being executed on every iteration of the For loop in my subroutine above):
If my_cbx.Tag = "PresetSelectedValue" Then
Exit Sub
End If