81

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Boardy
  • 35,417
  • 104
  • 256
  • 447
  • 1
    Try SelectedItem. And why are you using typename ComboBox as variable name?! – The Smallest Dec 04 '10 at 02:30
  • I'm not actually using ComboBox as the variable name. I should have made it clearer the combo box is actually cboType so I am using cboType.SelectedValue.toString(). I have tried selectedItem but it doesn't just give me the value it also shows System.Windows.Controls.ComboBoxItem: Software. Software being the value name which I only want that value so the rest before hand. Thanks for your help – Boardy Dec 04 '10 at 16:50
  • I interpreted "WF" as meaning "Windows Forms", not "Windows Workflow Foundation". What is correct? (Respond by editing your question, not here in comments.) – Peter Mortensen Apr 19 '18 at 13:38
  • @PeterMortensen I'm not sure what you're getting at, the question says WPF at every point, never WF – Boardy Apr 19 '18 at 17:17

25 Answers25

101

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();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Boardy
  • 35,417
  • 104
  • 256
  • 447
  • 5
    very strange. This row: 'ComboBoxItem typeItem = (ComboBoxItem)cboType.SelectedItem;' causes an error for me... – Guy Cohen Apr 11 '15 at 08:15
  • @GuyCohen its supposed to be ComboBox not ComboBoxItem – imGreg Sep 05 '15 at 04:07
  • @Tariq You're probably better off posting a new question as need to see the code to help really. But it looks like you trying to get the value from a DataGrid instead of a Combo Box – Boardy Mar 06 '16 at 23:58
  • string text = ((ComboBoxItem)comboBox.SelectedItem).Content.ToString(); – Helio Passarelli Apr 20 '22 at 13:58
  • This solution only worked part of the time for me. For some reason, I had to do this: string Name = NameList.SelectedItem is ComboBoxItem typeItem ? typeItem.Content.ToString() : NameList.SelectedItem.ToString(); – Rick Papo Aug 04 '22 at 12:45
94

Well.. I found a simpler solution.

String s = comboBox1.Text;

This way I get the selected value as string.

Austin Henley
  • 4,625
  • 13
  • 45
  • 80
Moile
  • 1,029
  • 7
  • 2
  • 25
    I tried this in the SelectionChanged event handler, but the text is still set to the old value not the newly selected item :( will use Boardy's answer. – Ben Dec 20 '13 at 00:28
  • 11
    this doesn't work, at least not when items are added dynamically in WPF. I don't understand so many upvotes. `((ComboBoxItem)comboBox1.SelectedItem).Content.ToString();` should be the right code – Bibaswann Bandyopadhyay Dec 09 '15 at 17:34
  • 2
    This answer will cause issues if it is used in a context with "SelectionChanged" and other things. '(MyCombobox.SelectedItem as ComboBoxItem).Content.ToString()' is a better solution in my opinion. – Travis Tubbs May 25 '17 at 17:46
  • 2
    It didnot work for me. I add combobox items dynamically. thanks – MindRoasterMir Jan 10 '19 at 20:57
  • 1
    comboBox1.Text will show the last selected value. On Selection_Changed, when a new value is selected, the above will still return the old value. – sandyiit Jun 10 '20 at 18:39
  • In C#WPF, "ComboBoxItem" does not contain a definition for "Text". So, this suggestion (String s = comboBox1.Text;) will not work properly! The solution as mentioned above by Ben Broadly is: private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { string chosenValue = e.AddedItems[0].ToString(); } – Ali Safari Jul 01 '20 at 21:04
  • This works great if you are using PowerShell to build WPF form. Tested and it also changes its value if selected item is changed. – Gregor Simončič Dec 01 '22 at 07:54
14

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();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kuntal Ghosh
  • 3,548
  • 2
  • 17
  • 21
11

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());
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
The Smallest
  • 5,713
  • 25
  • 38
  • 1
    I have tried doing this which does kind of work but not in the same way that old WF forms. In the old WF forms it would just give the selected value but now its printing: System.Windows.Controls.ComboBoxItem: Software. How do I only get the value like I could before without it printing the System.Windows.Controls.ComboBoxItem. Thanks for your help – Boardy Dec 04 '10 at 15:05
  • Good solution, simple and effective !! – Clint Apr 23 '18 at 12:05
7

How about these:

string yourstringname = (yourComboBox.SelectedItem as ComboBoxItem).Content.ToString();
Marc
  • 103
  • 17
b00sted 'snail'
  • 354
  • 1
  • 13
  • 27
7

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;
Benny
  • 3,899
  • 8
  • 46
  • 81
6

As a variant in the ComboBox SelectionChanged event handler:

private void ComboBoxName_SelectionChanged(object send ...
{
    string s = ComboBoxName.Items.GetItemAt(ComboBoxName.SelectedIndex).ToString();
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Oleg S.
  • 61
  • 1
  • 1
4

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();
}
Ben Broadley
  • 632
  • 6
  • 14
3

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"/>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
2

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);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
2

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.

vapcguy
  • 7,097
  • 1
  • 56
  • 52
1
private void usuarioBox_TextChanged(object sender, EventArgs e)
{
    string textComboBox = usuarioBox.Text;
}
Laurel
  • 5,965
  • 14
  • 31
  • 57
0
MsgBox(cmbCut.SelectedValue().ToString())
vidit
  • 6,293
  • 3
  • 32
  • 50
0

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

Combobox.SelectedValue
Laurel
  • 5,965
  • 14
  • 31
  • 57
basit raza
  • 661
  • 2
  • 6
  • 18
0

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mlarnt90
  • 176
  • 1
  • 4
  • 19
  • This will return `System.Windows.Controls.ComboBoxItem: YourItem` (for me). When I use `ComboBox.SelectionBoxItemStringFormat` (.NET 4.7) it will return the actual value as a string as defined within the `ComboBox.Content` property. – chriszo111 Aug 03 '18 at 12:59
0

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Machinarius
  • 3,637
  • 3
  • 30
  • 53
0

Write it like this:

String CmbTitle = (cmb.SelectedItem as ComboBoxItem).Content.ToString()
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MsDeveloper
  • 17
  • 1
  • 9
0

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));
        }
0
        // -----------------------------------------------------------------

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

        // -----------------------------------------------------------------
HemmaRoyD
  • 79
  • 1
  • 9
0

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
M. Fawad Surosh
  • 450
  • 7
  • 20
0
<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;
arhziz
  • 1
  • 1
0

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

combo.SelectedValue.ToString();
Gnqz
  • 3,292
  • 3
  • 25
  • 35
Carlos
  • 572
  • 1
  • 5
  • 13
-1

I use this code, and it works for me:

DataRowView typeItem = (DataRowView)myComboBox.SelectedItem; 
string value = typeItem.Row[0].ToString();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
-2

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
}
Marc
  • 103
  • 17
teikkhim
  • 29
  • 1
-3

It works for me:

System.Data.DataRowView typeItem = (System.Data.DataRowView)ComboBoxName.SelectedItem;
string value = typeItem.DataView.ToTable("a").Rows[0][0].ToString();
moondaisy
  • 4,303
  • 6
  • 41
  • 70