-1

I want to set the ComboBox yrComBox that selects the ComboBoxItem when I click the button.

Combobox in WPF:

<ComboBox x:Name="yrComBox" Grid.Column="3"
    Margin="0 0 10 0" FontSize="14" Padding="5" 
    FontFamily="Fonts/#Montserrat" Background="#fff">
    <ComboBoxItem Content="1st Year" Padding="5"/>
    <ComboBoxItem Content="2nd Year" Padding="5"/>
    <ComboBoxItem Content="3rd Year" Padding="5"/>
    <ComboBoxItem Content="4th Year" Padding="5"/>
</ComboBox>

Button:

<Button Grid.Column="2" x:Name="submitBtn"
    Margin="5 0 0 0" Cursor="Hand"
    Click="submitBtn_Click" Content="submit"
    Foreground="White" FontFamily="Fonts/#Montserrat"> 
</Button>

C#:

private void submitBtn_Click(object sender, RoutedEventArgs e)
{
    string year = "2nd Year";

    // set yrComBox here that selects a comboboxitem that its content is the variable year
}
janw
  • 8,758
  • 11
  • 40
  • 62

1 Answers1

0

If you want the SelectedItem

var year = yrComBox.SelectedItem;

If you want only the string you can:

var year = yrComBox.SelectedItem.ToString();

And if you want to check if this string exists in one of the items and if so display it in comboBox SelectedItem you can do so as follows:

private void submitBtn_Click(object sender, RoutedEventArgs e)
{
    string year = "2nd Year";
    foreach (var item in yrComBox.Items)
    {
        if (item is ComboBoxItem cbItem && cbItem.Content.Equals(year))
        {
            yrComBox.SelectedItem = cbItem;
        }
    }
}
Ohad Cohen
  • 597
  • 4
  • 9