Get selected value from combo box in C# WPF

C#WpfCombobox

C# Problem Overview


I have just started using WPF forms instead of Windows Forms forms. In a Windows Forms form I could just do:

ComboBox.SelectedValue.toString();

And this would work fine.

How do I do this in WPF? It doesn't seem to have the option.

C# Solutions


Solution 1 - C#

I have figured it out a bit of a strange way of doing it compared to the old WF forms:

ComboBoxItem typeItem = (ComboBoxItem)cboType.SelectedItem;
string value = typeItem.Content.ToString();

Solution 2 - C#

Well.. I found a simpler solution.

String s = comboBox1.Text;

This way I get the selected value as string.

Solution 3 - C#

My XAML is as below:

<ComboBox Grid.Row="2" Grid.Column="1" Height="25" Width="200" SelectedIndex="0" Name="cmbDeviceDefinitionId">
    <ComboBoxItem Content="United States" Name="US"></ComboBoxItem>
    <ComboBoxItem Content="European Union" Name="EU"></ComboBoxItem>
    <ComboBoxItem Content="Asia Pacific" Name="AP"></ComboBoxItem>
</ComboBox>

The content is showing as text and the name of the WPF combobox. To get the name of the selected item, I have follow this line of code:

ComboBoxItem ComboItem = (ComboBoxItem)cmbDeviceDefinitionId.SelectedItem;
string name = ComboItem.Name;

To get the selected text of a WPF combobox:

string name = cmbDeviceDefinitionId.SelectionBoxItem.ToString();

Solution 4 - C#

Ensure you have set the name for your ComboBox in your XAML file:

<ComboBox Height="23" Name="comboBox" />

In your code you can access selected item using SelectedItem property:

MessageBox.Show(comboBox.SelectedItem.ToString());

Solution 5 - C#

It depends what you bound to your ComboBox. If you have bound an object called MyObject, and have, let's say, a property called Name do the following:

MyObject mo = myListBox.SelectedItem as MyObject;
return mo.Name;

Solution 6 - C#

How about these:

string yourstringname = (yourComboBox.SelectedItem as ComboBoxItem).Content.ToString();

Solution 7 - C#

As a variant in the ComboBox SelectionChanged event handler:

private void ComboBoxName_SelectionChanged(object send ...
{
    string s = ComboBoxName.Items.GetItemAt(ComboBoxName.SelectedIndex).ToString();
}

Solution 8 - C#

I had a similar issue and tried a number of solutions suggested in this thread but found that the SelectionChanged Event was firing before the ComboBox item had actually updated to show the new selection (i.e. so it always gave the contents of the combobox prior to the change occurring).

In order to overcome this, I found that it was better to use the e parameter that is automatically passed to the event handler rather than trying to load the value directly from the combo box.

XAML:

<Window.Resources>
    <x:Array x:Key="Combo" Type="sys:String">
        <sys:String>Item 1</sys:String>
        <sys:String>Item 2</sys:String>
    </x:Array>
</Window.Resources>
<Grid>
    <ComboBox Name="myCombo" ItemsSource="{StaticResource Combo}" SelectionChanged="ComboBox_SelectionChanged" />
    <TextBlock Name="MyTextBlock"></TextBlock>
</Grid>

C#:

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    string chosenValue = e.AddedItems[0].ToString();
}

Solution 9 - C#

Solving this problem is simple. All I did was to add "SelectedValuePath" to my XAML code and bind it to my model property that I want to return with the combobox.

<ComboBox SelectedValuePath="_Department"
          DisplayMemberPath="_Department"
          Height="23"
          HorizontalAlignment="Left"
          ItemsSource="{Binding}"
          Margin="-58,1,0,5"
          Name="_DepartmentComboBox"
          VerticalAlignment="Center"
          Width="268"/>

Solution 10 - C#

Create a ComboBox SelectionChanged Event and set ItemsSource="{Binding}" in the WPF design:

Code:

private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    string ob = ((DataRowView)comboBox1.SelectedItem).Row.ItemArray[0].ToString();
    MessageBox.Show(ob);
}

Solution 11 - C#

This largely depends on how the box is being filled. If it is done by attaching a DataTable (or other collection) to the ItemsSource, you may find attaching a SelectionChanged event handler to your box in the XAML and then using this in the code-behind useful:

private void ComboBoxName_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ComboBox cbx = (ComboBox)sender;
    string s = ((DataRowView)cbx.Items.GetItemAt(cbx.SelectedIndex)).Row.ItemArray[0].ToString();
}

I saw 2 other answers on here that had different parts of that - one had ComboBoxName.Items.GetItemAt(ComboBoxName.SelectedIndex).ToString();, which looks similar but doesn't cast the box to a DataRowView, something I found I needed to do, and another: ((DataRowView)comboBox1.SelectedItem).Row.ItemArray[0].ToString();, used .SelectedItem instead of .Items.GetItemAt(comboBox1.SelectedIndex). That might've worked, but what I settled on was actually the combination of the two I wrote above, and don't remember why I avoided .SelectedItem except that it must not have worked for me in this scenario.

If you are filling the box dynamically, or with ComboBoxItem items in the dropdown directly in the XAML, this is the code I use:

private void ComboBoxName_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ComboBox cbx = (ComboBox)sender;
    string val = String.Empty;
    if (cbx.SelectedValue == null)
        val = cbx.SelectionBoxItem.ToString();
    else
        val = cboParser(cbx.SelectedValue.ToString());
}

You'll see I have cboParser, there. This is because the output from SelectedValue looks like this: System.Windows.Controls.Control: Some Value. At least it did in my project. So you have to parse your Some Value out of that:

private static string cboParser(string controlString)
{
    if (controlString.Contains(':'))
    {
        controlString = controlString.Split(':')[1].TrimStart(' ');
    }
    return controlString;
}

But this is why there are so many answers on this page. It largely depends on how you are filling the box, as to how you can get the value back out of it. An answer might be right in one circumstance, and wrong in the other.

Solution 12 - C#

private void usuarioBox_TextChanged(object sender, EventArgs e)
{
    string textComboBox = usuarioBox.Text;
}

Solution 13 - C#

It's the same principle.

You can either use SelectedIndex and use ComboBox.Items[SelectedIndex].ToString(). Or just ComboBox.SelectedItem and cast it to any type you need :)

Solution 14 - C#

MsgBox(cmbCut.SelectedValue().ToString())

Solution 15 - C#

To get the value of the ComboBox's selected index in C# use:

Combobox.SelectedValue

Solution 16 - C#

Actually you can do it the following way as well.

Suppose your ComboBox name is comboBoxA. Then its value can be gotten as:

string combo = comboBoxA.SelectedValue.ToString();

I think it's now supported since your question is five years old.

Solution 17 - C#

Write it like this:

String CmbTitle = (cmb.SelectedItem as ComboBoxItem).Content.ToString()

Solution 18 - C#

if you want to get the value and validate it you can do something like this

string index = ComboBoxDB.Text;
        if (index.Equals(""))
        {                
            MessageBox.Show("your message");
        }
        else
        {
            openFileDialog1.ShowDialog();
            string file = openFileDialog1.FileName;
            reader = new StreamReader(File.OpenRead(file));
        }

Solution 19 - C#

        // -----------------------------------------------------------------

        private void onSelectionChanged(object sender, 
                                        SelectionChangedEventArgs e)
        {
            String result = ((ComboBox)sender).SelectedItem.ToString();
            // do something with result
        }

        // -----------------------------------------------------------------

Solution 20 - C#

I found this useful. I am leaving it out here just in case if someone needs it:

To get the value:

(comboBox1.SelectedItem as dynamic).Value

To get the text:

(comboBox1.SelectedItem as dynamic).Text

Solution 21 - C#

<ComboBox x:Name="TestComboBox" SelectionChanged="TestComboBox_SelectionChanged" Padding="2">
    <ComboBoxItem>Item 1</ComboBoxItem>
    <ComboBoxItem>Item 2</ComboBoxItem>
</ComboBox>

Method 1

string content = (((sender as ComboBox).SelectedValue) as ComboBoxItem).Content.ToString();

Method 2

string content = (string)((ComboBoxItem)((ComboBox)sender).SelectedValue).Content;

Solution 22 - C#

A simple solution that works for me is:

string name = (string)combobox.SelectedItem

Solution 23 - C#

You can extract the values through the attribute SelectedValue. Like this:

combo.SelectedValue.ToString();

Solution 24 - C#

I use this code, and it works for me:

DataRowView typeItem = (DataRowView)myComboBox.SelectedItem; 
string value = typeItem.Row[0].ToString();

Solution 25 - C#

XAML:

<ComboBox Height="23" HorizontalAlignment="Left" Margin="19,123,0,0" Name="comboBox1" VerticalAlignment="Top" Width="33" ItemsSource="{Binding}" AllowDrop="True" AlternationCount="1">
    <ComboBoxItem Content="1" Name="ComboBoxItem1" />
    <ComboBoxItem Content="2" Name="ComboBoxItem2" />
    <ComboBoxItem Content="3" Name="ComboBoxItem3" />
</ComboBox>

C#:

if (ComboBoxItem1.IsSelected)
{
    // Your code
}
else if (ComboBoxItem2.IsSelected)
{
    // Your code
}
else if(ComboBoxItem3.IsSelected)
{
    // Your code
}
        

Solution 26 - C#

It works for me:

System.Data.DataRowView typeItem = (System.Data.DataRowView)ComboBoxName.SelectedItem;
string value = typeItem.DataView.ToTable("a").Rows[0][0].ToString();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBoardyView Question on Stackoverflow
Solution 1 - C#BoardyView Answer on Stackoverflow
Solution 2 - C#MoileView Answer on Stackoverflow
Solution 3 - C#Kuntal GhoshView Answer on Stackoverflow
Solution 4 - C#The SmallestView Answer on Stackoverflow
Solution 5 - C#BennyView Answer on Stackoverflow
Solution 6 - C#b00sted 'snail'View Answer on Stackoverflow
Solution 7 - C#Oleg S.View Answer on Stackoverflow
Solution 8 - C#Ben BroadleyView Answer on Stackoverflow
Solution 9 - C#Myron WilliamView Answer on Stackoverflow
Solution 10 - C#Vinay KumarView Answer on Stackoverflow
Solution 11 - C#vapcguyView Answer on Stackoverflow
Solution 12 - C#Maxson JordanView Answer on Stackoverflow
Solution 13 - C#MachinariusView Answer on Stackoverflow
Solution 14 - C#PoramateView Answer on Stackoverflow
Solution 15 - C#basit razaView Answer on Stackoverflow
Solution 16 - C#Mlarnt90View Answer on Stackoverflow
Solution 17 - C#MsDeveloperView Answer on Stackoverflow
Solution 18 - C#Johan CamargoView Answer on Stackoverflow
Solution 19 - C#HemmaRoyDView Answer on Stackoverflow
Solution 20 - C#M. Fawad SuroshView Answer on Stackoverflow
Solution 21 - C#arhzizView Answer on Stackoverflow
Solution 22 - C#steven01804View Answer on Stackoverflow
Solution 23 - C#CarlosView Answer on Stackoverflow
Solution 24 - C#SantiagoView Answer on Stackoverflow
Solution 25 - C#teikkhimView Answer on Stackoverflow
Solution 26 - C#Omid TavanaView Answer on Stackoverflow