C # Windows Forms Generic Object

3

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!

    
asked by anonymous 12.05.2016 / 00:13

2 answers

2

To access the content of cmbOpcoes.SelectedItem you have to convert it to an object (Class) that contains the properties, since your items are anonymous, you can use dynamic to access properties. >

See an example:

dynamic obj=cmbOpcoes.SelectedItem;
int id=obj.Id
string name=obj.Name;
    
12.05.2016 / 02:11
0

According to the MSDN , you can get the index with SelectedIndex same and the option text 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());
}
    
12.05.2016 / 01:01