C# Windows Forms Generic Object

Asked

Viewed 87 times

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!

2 answers

2


To access the contents of cmbOpcoes.SelectedItemyou have to convert it to an object(Class) that contains the properties, as your items are anonymous, you can use the dynamic to access the properties.

Take an example:

dynamic obj=cmbOpcoes.SelectedItem;
int id=obj.Id
string name=obj.Name;
  • 1

    Excellent! It worked great! Thank you, Tiago!

  • 3

    @Felipebulle You can choose the answer as "correct" by clicking on the bottom of the arrows to vote.

  • Perfect, marked!

0

According to the MSDN, you can get the content with SelectedIndex same and the text of the option with (SelectedItem as Object).ToString().

private void showSelectedButton_Click(object sender, System.EventArgs e) {
    int selectedIndex = comboBox1.SelectedIndex;
    Object selectedItem = comboBox1.SelectedItem;

    MessageBox.Show("Selected Item Text: " + selectedItem.ToString() + "\n" +
                    "Index: " + selectedIndex.ToString());
}
  • Thanks for the suggestion, Daniel! I’ve seen it, but it doesn’t really work. The index is not the ID. And selectedItem.toString() brings the result I mentioned in the question. But still, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.