H Aßdøµ
H Aßdøµ

Reputation: 3055

Find the index of an item in ComboBox

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>

Upvotes: 3

Views: 10356

Answers (3)

Scott Ridings
Scott Ridings

Reputation: 844

I had the same problem. I solved it like this.

For i = 0 To comboBox.Items.Count - 1
    If comboBox.Items(i).ToString = "searchString" Then
        comboBox.SelectedIndex = i
        Exit For
    End If
Next i

This will make the selection of the string value you're searching for.

Upvotes: 0

x21999125x
x21999125x

Reputation: 1

To use combobox.items.indexof, you need to put String in combobox, like this:

<ComboBox x:Name="Combobox1" HorizontalAlignment="Left" Margin="504,8,0,0" VerticalAlignment="Top" Width="120" Height="25">
    <System:String>Item1</System:String>
    <System:String>Item2</System:String>
    <System:String>Item3</System:String>
</ComboBox>

Then when you use Combobox1.items.indexof("Item2") it will return 1.

Upvotes: 0

mm8
mm8

Reputation: 169200

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);

Upvotes: 7

Related Questions