Igor Levashov
Igor Levashov

Reputation: 328

Getting property value in ComboBox in WPF

I have a comboBox and it is binded to list (from database, using entity framework). I would like to get an AdId of the selected item(object) on SelectionChanged of comboBox.

public class Ad
{          
    public int AdId { get; set; }
    public string AdContent { get; set; }
}

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ComboBox cmd = (ComboBox) sender;
    int AdId = cmd.SelectedItem;

    ???????????? I'm stuck here how to get AdId from SelectedItem... tried SelectedValue and SelectedValuePath... didn't work
}

Upvotes: 0

Views: 117

Answers (2)

Vijay
Vijay

Reputation: 673

Set SelectedValuePath="AdId"

And get selected value from code as follow,

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ComboBox cmd = (ComboBox) sender;
    int AdId = (int)cmd.SelectedValue;


}

enter image description here

Upvotes: 3

sujith karivelil
sujith karivelil

Reputation: 29036

The cmd.SelectedItem property of the ComboBox will returns an object, you can cast them to your own business object. and then you can easily access its properties like the following:

int AdId = ((Ad)cmd.SelectedItem).AdId ;
string AdContent =  ((Ad)cmd.SelectedItem).AdContent; 

Upvotes: 3

Related Questions