I have a Desktop application in C # and need to load a dropdown with an "All" option and the rest coming from a database table. To load the dropdownlist I did something like this:
cmbOpcoes.Items.Add(new { Id = 0, Name = "Todos" });
foreach (opcao o in db.opcao.OrderBy(c => c.nome).ToList())
{
cmbOpcoes.Items.Add(new { Id = opcao.id, Name = opcao.nome.ToString() });
}
cmbOpcoes.ValueMember = "Id";
cmbOpcoes.DisplayMember = "Name";
cmbOpcoes.SelectedIndex = 0;
And that works out well! It loads the options and comes default with the "All" option selected. The problem occurs when I have get the option populated by the user. The traditional:
cmbOpcoes.SelectedValue
comes with null value. The option:
cmbOpcoes.SelectedIndex
does not come null, but it does not contain the ID but rather the index of the value in the dropdown. The closest I needed was the
cmbOpcoes.SelectedItem
With the mouse over it, I see that it has an object {Id="3", Name="Option X"}, however I can not access these properties.
What code do I need to access this ID, since what do I need?
Thank you!