I have seen how to select the item from the index by code behind, but how can i select it from code behind knowing the string of the item?
combobox code xaml:
<ComboBox x:Name="ComboBoxOne" VerticalAlignment="Center" HorizontalAlignment="Center" Height="40" Width="200"> <ComboBoxItem Content="blue"/> <ComboBoxItem Content="red"/> <ComboBoxItem Content="green"/> </ComboBox>
combobox code behind:
ComboBoxOne.SelectedIndex = 1;
But how to select the item knowing for example green? Is possible?
I tried with ComboBoxOne.PlaceholderText
But then I can not use the selecteditem.
Thanks in advance!Answer1:
First you need to get the
Items of the
ComboBox as a
List to find the Index of the item that you want to select by string. Since this will be a
List<String> you can do something like below.
List<String> lstItems = ComboBoxOne.Items .Cast<ComboBoxItem>() .Select(item => item.Content.ToString()) .ToList();
and then you can get the index using
Linq and assign it to Selected Index. Like below.
ComboBoxOne.SelectedIndex = lstItems.FindIndex(a => a.Equals("green"));