Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the index of an item in ComboBox

Tags:

combobox

wpf

How can I find value index from ComboBox? I tried this but it always returns -1;

sexCombo.SelectedIndex = sexCombo.Items.IndexOf(teacherInfo["sex"].ToString());

Here how the ComboBox items are added:

<ComboBox x:Name="sexCombo" Margin="5,20,10,0" VerticalAlignment="Top" Width="100" Style="{StaticResource MaterialDesignFloatingHintComboBox}" materialDesign:HintAssist.Hint="الجنس" HorizontalContentAlignment="Left" Height="45" VerticalContentAlignment="Bottom">
        <ComboBoxItem Content="ذكر"/>
        <ComboBoxItem Content="أنثى"/>
</ComboBox>
like image 944
H Aßdøµ Avatar asked Dec 07 '25 08:12

H Aßdøµ


1 Answers

The Items collection of the ComboBox contains ComboBoxItems so you need to get the index of the corresponding ComboBoxItem element. Try this:

var comboBoxItem = sexCombo.Items.OfType<ComboBoxItem>().FirstOrDefault(x => x.Content.ToString() == teacherInfo["sex"].ToString());
int index = sexCombo.SelectedIndex = sexCombo.Items.IndexOf(comboBoxItem);
like image 189
mm8 Avatar answered Dec 10 '25 09:12

mm8