Getting the text of the selecteditem in Combobox

When you look at the Text property in the SelectionChanged event of the ComboBox it returns the prior value
here is a way to get the right value (cb1 is the name of the ComboBox)

Add this in Window loaded event

DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(ComboBox.TextProperty, typeof(ComboBox));

dpd.AddValueChanged(cb1, OnTextChanged);
 

and here is the handler

private void OnTextChanged(object sender, EventArgs args)
        {
            MessageBox.Show(cb1.Text);
        }

Advertisements

9 thoughts on “Getting the text of the selecteditem in Combobox

  1. So, I did this in VB:

    Dim dpd As DependencyPropertyDescriptor

    dpd = DependencyPropertyDescriptor.FromProperty(ComboBox.TextProperty, GetType(ComboBox))

    dpd.AddValueChanged(cb1, AddressOf OnTextChanged)

    And then:

    Private Sub OnTextChanged(ByVal sender As Object, ByVal args As EventArgs)

    End Sub

    This works fine in VB. But, WHY would they do such a thing!!

  2. No dependency property is necessary for getting the text. this code worked for me:

    private void ComboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
    string currentText = ComboBox1.SelectedValue as string;
    }

  3. if the displaymemberpath and selectedvaluepath are same then the value and display text will be the same and your code will work

  4. private void ComboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
    var selectedValue = ((ComboBox)e.OriginalSource).SelectedValue;
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s