-2

I am populating a combobox by connecting a datasource from an sql statement.

dt = select Name as [Name], Code as [Id] from Table

Then I want to se the default value of the combobox to "Nick" which I am locating with the following code

    For Each i as DataRowView in comboBox.Items

    If i("Name").ToString="Nick" Then
    comboBox.SelectedIndex=selectedCount
    Exit For
    End If

selectedCount=selectedCount +1
Next

This will correctly display "Nick" as the default in the comboBox, but when I go and get the selectedValue with the following code it is getting the selected index of the first item in the list not the delfault item "Nick".

When I click a button and look at the SelectedIndex of the combobox it is set back to 0 eventhough it displays the correct selectedValue in the comboxbox.

item=comboBox.SelectedValue.ToString

How do I get the selected Value I defaulted the combobox to?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Nick LaMarca
  • 8,076
  • 31
  • 93
  • 152
  • possible duplicate of [ComboBox.SelectedValue not working](http://stackoverflow.com/questions/18730262/combobox-selectedvalue-not-working). Note quite the same, but I'd certainly look at using `SelectedItem` instead. – James Thorpe Dec 02 '14 at 16:37
  • Can't you use `comboBox.SelectedItem = i`? BTW, don't forget to close the quotation mark after "Nick". – Andrew Dec 02 '14 at 16:38

1 Answers1

0

This worked for me:

item = comboBox.Items(comboBox.SelectedIndex).ToString

If your SelectedIndex somehow gets reverted back to 0, then declare an int and in your loop, set the ints value to the selectedCount. Then set the item by using the int as the comboBoxe's item index:

Dim index as Int = 0

For Each i as DataRowView in comboBox.Items

  If i("Name").ToString="Nick" Then
  comboBox.SelectedIndex=selectedCount
  index = selectedCount
  Exit For
  End If

  selectedCount=selectedCount +1
Next

item = comboBox.Items(index).ToString
Ntellect13
  • 331
  • 1
  • 5