Search code examples
c#.netwpfcombobox

How can I assign the value of a selected item in a combobox?


I have a combobox that already contains default values and I would like to assign a value to the combobox so that at runtime, the assigned value appears selected.

This is the combobox

<ComboBox x:Name="MyComboBox" VerticalAlignment="Center" Width="50" Padding="1" Height="23">
     <ComboBoxItem IsSelected="True">A</ComboBoxItem>
     <ComboBoxItem>B</ComboBoxItem>
     <ComboBoxItem>C</ComboBoxItem>
     <ComboBoxItem>D</ComboBoxItem>
     <ComboBoxItem>E</ComboBoxItem>
     <ComboBoxItem>F</ComboBoxItem>
     <ComboBoxItem>G</ComboBoxItem>
     <ComboBoxItem>H</ComboBoxItem>
     <ComboBoxItem>I</ComboBoxItem>
     <ComboBoxItem>K</ComboBoxItem>
     <ComboBoxItem>L</ComboBoxItem>
     <ComboBoxItem>M</ComboBoxItem>
     <ComboBoxItem>N</ComboBoxItem>
</ComboBox>

The values that I am assigning will be one of the default ones. Therefore, I don't want to add a new item. Just to display the item that I have assigned as selected.

This is what I have tries to no success:

//I get a value from reading a datareader

string MyValue = datareader.GetString(0);

// I assign the value to the combobox:

MyComboBox.SelectedItem = MyValue; //Attempt 1

MyComboBox.SelectedValue = MyValue; //Attempt 2

MyComboBox.Text= MyValue; //Attempt 3

MyComboBox.SelectedIndex = MyValue; //Attempt 4. Throws an error as MyValue is a string

Thanks for your help!


Solution

  • Have you tried this method:

    Using visual studio, on the design view or .xaml if you double click the ComboBox it will autogenerate code for SelectionChanged in the .xaml.cs file. In addition, on the .xaml, when you click the ComboBox it will tell you the name of the object on the properties tab. Mine is comboBox in this example:

    private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        string selectedItem = comboBox.Items[comboBox.SelectedIndex].ToString();
        Console.WriteLine(selectedItem);
    }
    

    For simplicity sake I just have it printing to the console, which will show up when you exit the program.

    And so to change the value of what is shown in the comboBox at runtime for whatever reason that might be you can use something like this:

    comboBox.SelectedItem = comboBox.Items[0];
    

    Which would set it to the first item that you added to the comboBox whenever the user makes any selection.

    From what I understand, you would need the text to be assigned to an item already in the ComboBox:

    string MyValue = "asd";
    comboBox.Items.Add(MyValue);
    comboBox.Text = MyValue;