[RESOLVED] Getting bound ComboBox selected item text
Hi Folks
I have a Combobox populated with MAC address strings from a SQL server DB (using Entity Framwork)
VB Code:
Public Class Form1
Dim myContext As New MySqlDataEntities
Dim burnRackBay As New BurnRackBay
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
ComboBox1.DataSource = myContext.BurnRackBays
ComboBox1.DisplayMember = "Mac"
ComboBox1.SelectedIndex = -1
End Sub
However when getting the text of the selected item to use in a new L2E query the only way that seems to work is to use ComboBox.Text
VB Code:
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
If ComboBox1.SelectedIndex >= 0 Then
Label4.Text = ComboBox1.Text
End If
End Sub
But when I do this, when the form loads the label text is immediately set to the first item in the list instead of just being left blank, as the ComboBox is (as I set its index to -1 in Form1.Load)
Is there a better way of getting the selected string, that is the *actual* string *currently* selected
EDIT: Just noted that this does not occur if I remove the If from the selectedIndexChanged event... does this mean that the event is firing on form load but before the form.load event sub runs?
Re: Getting bound ComboBox selected item text
Quote:
Just noted that this does not occur if I remove the If from the selectedIndexChanged event... does this mean that the event is firing on form load but before the form.load event sub runs?
Er, not quite. If it ran before the form load it wouldn't have anything to select, would it. The default on binding is to select item 0. The event fires and the label gets the text. You then change the selected index to -1 and the event fires again but as it's -1 no change is effected in the label. I'm not really sure why you need the label to say what the combobox already says, to be honest, but the simplest solution is an Else Label4.Text = ""
Re: Getting bound ComboBox selected item text
Hmm, OK. I think I need to make this test projet more accurately represent my use case before I go any further...
Thanks dunfiddlin :)