SelectedIndex in comboBox does not return the correct integer in some cases

after programming whiling in C #, I will find out when we have equal elements in comboBox, we cannot get the correct selectIndex. Imagine we have a ComboBox with these elements:

enter image description here

And I want to get 2 when I select the third item in ComboBox, but I always get 0. And I want to get 4 when I select the fifth item in ComboBox, but I always get 3.

I think SelectedIndex in a ComboBox always returns the first ComboBox element.

How can I get the selected item index from a comboBox with equal items?

+4
source share
4 answers

I suspect you are binding to a List String.
String is a reference type, but it overrides = and finds the first match of values.
Create a simple class that has only one row property.

 public class SimpleString { public string StrValue { get; set; } public SimpleString() { } public SimpleString(string strValue) { StrValue = StrValue; } } 
+2
source

MainWindow.xaml.cs:

 public partial class MainWindow : Window { private List<String> list = new List<string>(); public List<String> List { get { return this.list; } set { this.list = value; } } public MainWindow() { InitializeComponent(); list.Add("methode"); list.Add("methode"); list.Add("methode"); list.Add("methode2"); list.Add("methode2"); this.DataContext = this; } private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e) { MessageBox.Show(comboBox1.SelectedIndex.ToString()); } } 

MainWindow.xaml:

 <Window x:Class="Temp2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <ComboBox Height="23" HorizontalAlignment="Left" Name="comboBox1" VerticalAlignment="Top" Width="120" SelectionChanged="comboBox1_SelectionChanged" ItemsSource="{Binding List}" /> </Grid> </Window> 

works great for me. Can you clarify your question? Keep in mind that I tried different types and always got a working result.

+1
source

You can create a flag model class that will contain the name and identifier properties. Then run the comboBox'es DisplayMember and DataMember properties for these properties. Now set the DataSource property to comboBox to the list of your custom elements.

Since the DataSource elements are now not equal (by reference), they will not be considered equal, and you can get SelectedValue . SelectedIndex will probably work as well, but this is not the best approach in this case.

0
source

I don’t understand that it has the same text with a different value, still use SelectedValue instead of SelectedIndex .

If you absolutely need a pointer, you can loop through list items ...

0
source

All Articles