Disaji
Disaji

Reputation: 99

KeyValue Pair combobox .text after saved on database

I handle two combobox whit follow code:

var Masters = new List<KeyValuePair<long, string>>();
using (var ctx = new GestioneCaricoEntities())
{
    var comti = ctx.ViewMasters.OrderBy(m => m.Lastname).ToList();
    foreach (var t in comti)
    {
        Masters.Add(new KeyValuePair<long, string>(t.Id, t.Lastname));
    }
}
cmbComteCaricazione.ItemsSource = Masters;

and

<ComboBox x:Name="cmbComteCaricazione" Margin="0,5,0,0" 
          DisplayMemberPath="Value" SelectedValuePath="Key" Width="110"  IsEditable="True" />

i save on database :

ts.IdComandanteCaricazione = (long?)cmbComteCaricazione.SelectedValue;

Question: everything go in the right way, the field of table in db has the idComandanteCaricazione but when i load the window again i like to see the Value in cmbComteCaricazione.text. how can i do it?

Upvotes: 1

Views: 19

Answers (1)

mm8
mm8

Reputation: 169340

You need to load the idComandanteCaricazione from the database and set the SelectedValue property of the ComboBox to it:

public MainWindow()
{
    InitializeComponent();
    this.Loaded += (s, e) =>
    {
        using (var ctx = new GestioneCaricoEntities())
        {
            ...
            cmbComteCaricazione.ItemsSource = Masters;
            cmbComteCaricazione.SelectedValue = ts.IdComandanteCaricazione;
        }

    };
}

Upvotes: 1

Related Questions