Set Selected value on combobox in WPF

Viewed 120

I have a simple WPF with a combobox; when I use new array as itemssource (COMMENTED LINE IN CODE), I can set the default value by setting SelectedValue="..." (a string from another query result. but when I use a query and reading from DB. adding items works, but the setting SelectedValue job does not work!

my xaml.cs code:

tempdbEntities mydb = new tempdbEntities();
public MainWindow()
{
    InitializeComponent();
    FillForm(1);
}

private void Window_Activated(object sender, EventArgs e)
{
    //cmbVendors.ItemsSource = new string[] { "ABC", "BCD", "EFG" };

    cmbVendors.ItemsSource = mydb.tbl_Company.Where(c => c.Id < 5).ToList();
    cmbVendors.DisplayMemberPath = "Name";    
}

private void FillForm(int ID0)
{    
    cmbVendors.SelectedValue = mydb.tbl_Company.Where(c => c.Id == ID0).Single().Name;    
}

Xaml code:

<Grid Margin="0,-41,0,0">
    <ComboBox Name="cmbVendors" HorizontalAlignment="Left" 
              Margin="474,102,0,0" VerticalAlignment="Top" 
              Width="231"/>    
</Grid>
2 Answers

Combobox's DisplayMemberPath will just control what need to be displayed; SelectedValue will be still of your Model type. You need to set

cmbVendors.SelectedValuePath = "Name";

This will make sure your cmbVendors's SelectedValue will hold Name.

what I want to do: this is an edit form. when the form is loaded, should fill all components in form, textboxes,comboboxes,... by data from table. cmbVendors like other components should show the content got from DB, and if user wanted to change it, he can do. and click submit....

I have edited the FillForm Method as bellow:

private void FillForm(int ID0)
        {
            cmbVendors.SelectedValuePath = "Name";
            cmbVendors.SelectedValue = mydb.tbl_Company.Where(c => c.Id == ID0).Single().Name;

        }

Thanks. It works well!

Related