Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select value on a databound combobox?

I have a ComboBox that's been bound to a DataView that's taken a filled DataTable. This DataTable has three columns. Before the DataView is bound to the ComboBox I add another column and set some values.

   Dim table As DataTable = _retrieve.GetAllVersionsTable()
    table.Columns.Add("FirstRow", GetType(Boolean))

    Dim row As DataRow = table.NewRow()
    row("ID") = -1
    row("SomeValue") = -1
    row("SomeText") = "N/A"
    row("FirstRow") = True 'Fort sorting...

    Dim view As DataView = New DataView(table)
    view.Sort = "FirstRow DESC, SomeText DESC"

    table.Rows.InsertAt(row, 0)

    comboBox.DataSource = view
    comboBox.ValueMember = "ID"
    comboBox.DisplayMember = "SomeText"

Later on, I retrieve the same data and create a new DataTable and bind it to a DataGridView in another form. From this form I set a value for the identity column from selected row in the DataGridView.

When I get back to the first form, with the ComboBox, I wish to select the ComboBox row that has the same value, that I set from the second form, tied to its ValueMember property. I thought that SelectedValue would work for this but it doesn't. What else can I do?

comboBox.SelectedValue = myIdentityValue

Since the rows are different I can't use SelectedItem either. Is there a way I can select the appropriate row without having to loop over all existing rows?

like image 318
Zolomon Avatar asked Nov 15 '22 01:11

Zolomon


1 Answers

According to MSDN:

SelectedValue: Gets or sets the value of the member property specified by the ValueMember property.

So according to documentation, doing something like this should work, assuming 123 is an ID present in the combobox, because ID has been set as the ValueMember:

comboBox.SelectedValue = 123

If you can't get it to work (maybe binding with DataView doesn't work well?), then you could use SelectedIndex which always works.

like image 59
Meta-Knight Avatar answered Dec 19 '22 00:12

Meta-Knight