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.开发者_StackOverflow中文版 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?
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.
For anybody that comes across this topic, has the same problems like Zolom or me. I think I found a important thing that is not documented:
You must pass the same datatype to .SelectedValue. If not the search will fail without any hint.
Let's say you fill your DataSource with with a database and have lets say integer as value-field you have to pass an integer to the SelectedIndex. If it was string you pass a string.
I hope this helps...
That issue you can solve setting to Nothing the property datasource before than set the datasource:
Combobox.datasource=nothing
Combobox.DisplayMember="Data";
Combobox.ValueMember="ID";
Combobox.datasource = NewDataTable;
Combobox.SelectedValue = 4;
Use Combobox.text=""
. It will automatically change the selectedvalue property to your your entered text.
精彩评论