I
I
idShura2017-02-21 12:24:56
WPF
idShura, 2017-02-21 12:24:56

How to select item in comboBox by name?

How to select item in comboBox by name in WPF C#?
You can't do it like on WinForms in WPF:

comboBox2.SelectedIndex = comboBox2.Items.IndexOf("Вася");

I add the values ​​in the comboBox like this:
comboBox2.ItemsSource = r2.ResultData.DefaultView;
comboBox2.SelectedValuePath = r2.ResultData.DefaultView.Table.Columns["id"].ToString(); 
comboBox2.DisplayMemberPath = r2.ResultData.DefaultView.Table.Columns["name"].ToString();

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sumor, 2017-02-21
@idShura

Items is used for "item" work, and ItemsSource for connection of collections. You cannot work with them at the same time - either Items or ItemsSource.
So your code should look something like this:
But this will not work, since the elements in the ComboBox are the elements from the table as a whole, and not just the names. Therefore, it is better and more convenient to use the SelectedItem property, something like this:
Better yet, bind the comboBox2.SelectedItem property through Binding to some property of your model and use it.

D
d-stream, 2017-02-21
@d-stream

Wouldn't it be better to use binding ?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question