Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the data in comboBox C#

Tags:

c#

winforms

I have a combo box and I populated it this way:

DataTable dt = new DataTable();

using (SQLiteConnection conn = connection.Conn)
{               
    using (SQLiteCommand cmd = new SQLiteCommand(conn))
    {
        cmd.CommandText = "select id, description from category";
        conn.Open();

        using (SQLiteDataAdapter da = new SQLiteDataAdapter(cmd))
        {
            da.Fill(dtChargeCodes);
            comboBox1.DataSource = dt;
            comboBox1.DisplayMember = "description";
            comboBox1.ValueMember = "id";
        }                                       
    }               
}

What I'm trying to achive is to get the data of the selected item in the comboBox but when I tried to display it using MessageBox.Show(comboBox1.SelectedItem.ToString()); what I get is the type System.Data.DataRowView. not the actual value of the field description in the table category. Please help... thanks.

like image 406
yonan2236 Avatar asked Jul 18 '11 12:07

yonan2236


People also ask

How do I get the ComboBox selected value?

string strID = MyCombobox2. SelectedValue. ToString();

How do I get selected text in ComboBox?

You can use the SelectedText property to retrieve or change the currently selected text in a ComboBox control. However, you should be aware that the selection can change automatically because of user interaction.

How do I find the index of a ComboBox?

However, if you want to get the index of selected items in the combobox widget, then you can use the get() method. The get() method returns an integer of the selected item known as the index of the item.


2 Answers

Either use

comboBox1.SelectedText

or

((System.Data.DataRowView)(comboBox1.SelectedItem))["description"]

You may need to use the second method if you need to access the value in the SelectedIndexChanged event (see here)

like image 195
Patrick McDonald Avatar answered Oct 05 '22 10:10

Patrick McDonald


Try this:

MessageBox.Show(comboBox1.SelectedValue);
like image 38
Jason Down Avatar answered Oct 05 '22 11:10

Jason Down