109

C#, .NET 4.0, VS2010.

New to WPF. I have a ComboBox on my MainWindow. I hooked the SelectionChanged event of said combo box. However, if I examine the value of the combo box in the event handler, it has the old value. This sounds more like a "SelectionChanging" event, than a SelectionChanged event.

How do I get the new value of the ComboBox after the selection has actually happend?

Currently:

this.MyComboBox.SelectionChanged += new SelectionChangedEventHandler(OnMyComboBoxChanged);

...
private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
    string text = this.MyComboBox.Text;
}

Note, I get the same behaviour if I use the object being passed in the event args, e.g. e.OriginalSource.

2
  • 2
    I just stumbled over the same issue - thanks! Is that actually a bug, and it should have been named SelectionChanging in the first place?
    – Jan
    Commented Jan 17, 2012 at 17:19
  • Inspection of the source code of method ComboBox.OnSelectionChanged shows that it publishes the event and then processes the selected item. In a related problem, I used reflection to force it to process the selected item from my SelectionChanged event handler. Commented Oct 29, 2021 at 0:27

19 Answers 19

130

According to MSDN, e.AddedItems:

Gets a list that contains the items that were selected.

So you could use:

private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
    string text = (e.AddedItems[0] as ComboBoxItem).Content as string;
}

You could also use SelectedItem if you use string values for the Items from the sender:

private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
    string text = (sender as ComboBox).SelectedItem as string;
}

or

private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
    string text = ((sender as ComboBox).SelectedItem as ComboBoxItem).Content as string;
}

Since both Content and SelectedItem are objects, a safer approach would be to use .ToString() instead of as string

7
  • 13
    interesting ... it has the new value. And RemovedItems has the old. That event name is a bit if a misnomer, at least IMHO. When I see SelectionChanged, I expect the state of the object to, well, have changed. I can see how this gives us slightly more information though.
    – Matt
    Commented Jun 2, 2010 at 20:00
  • 1
    Yeah, I think its because the change has occurred, but has not be committed? Thats just a guess. You might be able to get the text of the selected item, see my edit.
    – SwDevMan81
    Commented Jun 2, 2010 at 20:02
  • 3
    ComboBox.SelectedItem does not have a property called Text, but you can do ComboBox.SelectedItem as string (though this may only work if you use string for the Items - not tested anything else)
    – musefan
    Commented Dec 19, 2013 at 10:51
  • 2
    Just string text = (string)e.AddedItems[0];
    – Igor Semin
    Commented Mar 13, 2015 at 12:41
  • 2
    Wish I could give 2 ups, your answer helped me twice in 2 different occasions
    – tbs
    Commented Sep 22, 2020 at 13:29
81

The correct value to check here is the SelectedItem property.

A ComboBox is a composite control with two of its parts being:

  1. The Text Part: the value in the this part corresponds to the Text property of the ComboBox.
  2. The Selector Part (i.e. the "drop-down" part): The selected item in this part corresponds to the SelectedItem property.

Expanded ComboBox Parts

The image above was taken immediately after the ComboBox was expanded (i.e. before selecting a new value). At this point both Text and SelectedItem are "Info", assuming the ComboBox items were strings. If the ComboBox items were instead all the values of an Enum called "LogLevel", SelectedItem would currently be LogLevel.Info.

When an item in the drop-down is clicked on, the value of SelectedItem is changed and the SelectionChanged event is raised. The Text property isn't updated yet, though, as the Text Part isn't updated until after the SelectionChanged handler is finished. This can be observed by putting a breakpoint in the handler and looking at the control:

ComboBox at breakpoint in SelectionChanged handler

Since the Text Part hasn't been updated at this point, the Text property returns the previously selected value.

2
  • 3
    Complete expanation and it helped realize my Binding was on the Text property instead of the correct SelectedItem.
    – cmousset
    Commented Oct 20, 2015 at 16:41
  • 2
    @DaveKidder Great example! +1 Commented Dec 7, 2018 at 13:24
54

Use the DropDownClosed event instead of selectionChanged if you want the current value of the combo box.

private void comboBox_DropDownClosed(object sender, EventArgs e)
{
   MessageBox.Show(comboBox.Text) 
}

Is really that simple.

3
  • 10
    @jvelez I think it won't fire when using a keyboard. Commented Aug 19, 2011 at 6:24
  • that sucks. NoviceProgrammer who knew...!
    – hidden
    Commented Apr 10, 2013 at 23:15
  • This worked for me. It is comical that it's not possible to easily get the selected value when the selection has changed. I am sure there is a good reason for it, but gosh.
    – Action Dan
    Commented Sep 13, 2021 at 10:05
11

This worked for me:

private void AppName_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
   ComboBoxItem cbi = (ComboBoxItem)AppName.SelectedItem;
   string selectedText = cbi.Content.ToString();
}
1
  • somehow only SelectedItem gets populated with the new item, not SelectedValue.
    – mauris
    Commented Aug 23, 2013 at 16:05
8

This worked for me:

private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
    var text = ((sender as ComboBox).SelectedItem as ComboBoxItem).Content as string;            
}
3
  • This is very important. The accepted answer does not explicitly show that sender contains the correct SelectedItem.
    – Jess
    Commented Mar 21, 2016 at 13:36
  • this throws an exception for me: System.NullReferenceException: 'Object reference not set to an instance of an object.' (... as System.Windows.Controls.ComboBoxItem) returned null.
    – Ali Safari
    Commented Dec 4, 2020 at 2:34
  • @Jess - I 100% agree. The accepted answer didnt work for me. This one did. Commented Dec 22, 2020 at 19:22
6

Following event is fired for any change of the text in the ComboBox (when the selected index is changed and when the text is changed by editing too).

<ComboBox IsEditable="True" TextBoxBase.TextChanged="cbx_TextChanged" />
0
1
private void OnMyComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
    string newItem = ((DataRowView) e.AddedItems[0]).Row.ItemArray[0].ToString();
}
2
  • 7
    Please don't provide code-only answers. Please give an explanation of why your solution is the answer.
    – Lee Taylor
    Commented Nov 24, 2012 at 12:59
  • System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'System.Data.DataRowView'.'
    – Ali Safari
    Commented Dec 4, 2020 at 2:42
1

The second option didn't work for me because the .Text element was out of scope (C# 4.0 VS2008). This was my solution...

string test = null;
foreach (ComboBoxItem item in e.AddedItems)
{
   test = item.Content.ToString();
   break;
}
1

If you really need the SelectionChanged event, then the best answer is SwDevMan81's answer. However, if you are starting with WPF, then you might want to learn how to do things the WPF way, which is different than the old Windows Forms days that used to rely on events like SelectionChanged, with WPF and Model View ViewModel pattern, you should use bindings. Here is a code example:

// In the Views folder: /Views/MyWindow.xaml:
// ...
<ComboBox ItemsSource="{Binding MyViewModel.MyProperties, RelativeSource={RelativeSource AncestorType=Window}}"
         SelectedItem="{Binding MyViewModel.MyProperty  , RelativeSource={RelativeSource AncestorType=Window}}" />
// ...



// In the Views folder: /Views/MyWindow.xaml.cs:
public partial class MyWindow : Window
{
    public  MyViewModelClass MyViewModel {
        get { return _viewModel; }
        private set { _viewModel = value;}
    }

    public MyWindow()
    {
        MyViewModel.PropertyChanged += MyViewModel_PropertyChanged;

    }

    void MyViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "MyProperty")
        {
            // Do Work
            // Put your logic here!
        }
    }
}

using System.ComponentModel;

// In your ViewModel folder: /ViewModels/MyViewModelClass.cs:
public class MyViewModelClass : INotifyPropertyChanged
{
    // INotifyPropertyChanged implementation:
    private void NotifyPropertyChanged(string propertyName = "") { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } }
    public event PropertyChangedEventHandler PropertyChanged;

    // Selected option:
    private string _myProperty;
    public  string  MyProperty {
        get { return _myProperty; }
        set { _myProperty = value; NotifyPropertyChanged("MyProperty"); }
    }

    // Available options:
    private List<string> _myProperties;
    public  List<string>  MyProperties {
        get { return _myProperties; }
        set { _myProperties = value; NotifyPropertyChanged("MyProperties"); }
    }

}
1
private void indBoxProject_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    int NewProjID = (e.AddedItems[0] as kProject).ProjectID;
    this.MyProject = new kProject(NewProjID);
    LoadWorkPhase();
}

The use of the e.AddedItems[0] as kProject where kProject is a class that holds the data worked for me as it was defaulting to the RemovedItems[0] before I have made this explicit distinction. Thanks SwDevMan81 for the initial information that answered this question for me.

0

I needed to solve this in VB.NET. Here's what I've got that seems to work:

Private Sub ComboBox1_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles ComboBox_AllSites.SelectionChanged
   Dim cr As System.Windows.Controls.ComboBoxItem = ComboBox1.SelectedValue
   Dim currentText = cr.Content
   MessageBox.Show(currentText)
End Sub
0

It's weird that SelectedItem holds the fresh data, whereas SelectedValue doesn't. Sounds like a bug to me. If your items in the Combobox are objects other than ComboBoxItems, you will need something like this: (my ComboBox contains KeyValuePairs)

var selectedItem = (KeyValuePair<string, string>?)(sender as ComboBox).SelectedItem;
if (!selectedItem.HasValue)
    return;

string selectedValue = selectedItem.Value.Value;  // first .Value gets ref to KVPair

ComboBox.SelectedItem can be null, whereas Visual Studio keeps telling me that a KeyValuePair can't be null. That's why I cast the SelectedItem to a nullable KeyValuePair<string, string>?. Then I check if selectedItem has a value other than null. This approach should be applicable to whatever type your selected item actually is.

0

Don't complicate things for no reason. Using SelectedValue property you can easily get a selected ComboBox value like this: YourComboBoxName.SelectedValue.ToString().

Behind the scene the SelectedValue property is defined as: SelectedValue{get; set;} this means you can use it to get or set the value of a ComboBox.

Using SelectedItem is not an efficient way to get a ComboBox value since it requires a lot of ramifications.

0

You can check SelectedIndex or SelectedValue or SelectedItem property in the SelectionChanged event of the Combobox control.

0

From SelectionChanged event of a combobox you can get the selected item text as follow:

        private void myComboBox_SelectionChanged (object sender, SelectionChangedEventArgs e)
        {
        ComboBoxItem comboBoxItem = (ComboBoxItem) e.AddedItems[0];
        string selectedItemText = comboBoxItem.Content.ToString();
        }
0

clean and easy - TextChanged

private void ComboBox1_TextChanged(object sender, EventArgs e)
    {
        MessageBox.Show(ComboBox1.Text);
    }
0

Following works for me to get current selection of ComboBox (c# / .net6):

private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) {
    string? text = ((ComboBoxItem)(sender as ComboBox).SelectedItem).Content as string;
    
    if(text != null){
        ...
    }
}
-3

This should work for you ...

int myInt= ((data)(((object[])(e.AddedItems))[0])).kid;
1
  • 2
    Can you explain how this answers the question? Commented Mar 30, 2015 at 1:29
-3

I solved this by using the DropDownClosed event because this fires slightly after the value is changed.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.