3
I have a Desktop application in C# and need to load a dropdown with an option "All" 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 so far it works well! It loads the options and comes default with the "All" option selected. The problem occurs when I have get the option filled by the user. The traditional:
cmbOpcoes.SelectedValue
comes with null value. Option:
cmbOpcoes.SelectedIndex
does not come null, but it does not contain the ID, but the value index in the dropdown. Closest to what was needed was the
cmbOpcoes.SelectedItem
With the mouse over it, I see that you have an object { id = "3", Name = "Option X" }, but I cannot access these properties.
What is the code to access this ID, because it’s the one I need?
Thank you!
Excellent! It worked great! Thank you, Tiago!
– Felipe Bulle
@Felipebulle You can choose the answer as "correct" by clicking on the bottom of the arrows to vote.
– Jéf Bueno
Perfect, marked!
– Felipe Bulle