How to select a value in the data drop-down list?

I have a ComboBox related to a DataView that took a populated DataTable . This DataTable has three columns. Before the DataView bound to a 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" 

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

When I return to the first form using ComboBox , I want to select the ComboBox line, which has the same value that I set from the second form, bound to the ValueMember property. I thought SelectedValue would work for this, but it is not. What else can I do?

 comboBox.SelectedValue = myIdentityValue 

Since the strings are different, I cannot use SelectedItem . Is there a way to select a suitable row without having to iterate over all existing rows?

+4
source share
4 answers

According to MSDN:

SelectedValue: Gets or sets the value of the property of the participant specified in the ValueMember property.

So, according to the documentation, something like this should work, assuming 123 is the identifier present in combobox, because the ID was set as ValueMember:

 comboBox.SelectedValue = 123 

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

+2
source

For everyone who is faced with this topic, there are the same problems as Zol or I. I think I found an important thing that is not documented:

You must pass the same data type to .SelectedValue. If the search does not end without any hints.

Say you populate your DataSource with a database and you can tell integer as value-field that you must pass an integer to SelectedIndex. If it is a string, you pass the string.

Hope this helps ...

0
source

In this problem, you may decide to set the Nothing data source for properties before setting the DataSource:

 Combobox.datasource=nothing Combobox.DisplayMember="Data"; Combobox.ValueMember="ID"; Combobox.datasource = NewDataTable; Combobox.SelectedValue = 4; 
0
source

Use Combobox.text="" . It will automatically change the selectedvalue property to your entered text.

-2
source

Source: https://habr.com/ru/post/1344086/


All Articles