Alen
Alen

Reputation: 1291

How to get value of ComboBox rather than text

I have a combobox cmbCourses and I am populating my this code

var _courses = new DatabaseHandler().GetAllCourses();
            foreach (var a in _courses)
            {
                ComboBoxItem item = new ComboBoxItem();
                item.Text = a.Value;
                item.Value = a.Key;

                cmbCourses.Items.Add(a.Value);
            }

 public Dictionary<int, String> GetAllCourses()
    {
        Dictionary<int, String> courses = new Dictionary<int, String>();

        var connection = DatabaseConnector.Instance();

        if(connection.IsConnect())
        {
            connection.Connection.Open();
            string query = "SELECT * FROM courses";
            cmd = new MySqlCommand(query, connection.Connection);
            cmd.Prepare();
            var result = cmd.ExecuteReader();

            while(result.Read())
            {
                courses.Add(result.GetInt16(0), result.GetString(1));
            }
        }
        connection.Connection.Close();

        return courses;
    }

But when I try to get key it shows value instead using this code

MessageBox.Show(cmbCourses.SelectedItem.ToString());

Upvotes: 3

Views: 202

Answers (3)

mm8
mm8

Reputation: 169370

You are only adding the value to the ComboBox. Add the KeyValuePair to the ComboBox and set the DisplayMemberPath and SelectedValuePath properties:

var _courses = new DatabaseHandler().GetAllCourses();
foreach (var a in _courses)
{
    cmbCourses.Items.Add(a);
}
cmbCourses.DisplayMemberPath = "Value";
cmbCourses.SelectedValuePath = "Key";

You can then get the key of the selected item like this:

var item = cmbCourses.SelectedItem as KeyValuePair<int, String>;
if (item != null)
    MessageBox.Show(item.Key);

Upvotes: 1

Md. Suman Kabir
Md. Suman Kabir

Reputation: 5453

Seems you have problem in adding items to your combobox, you are adding only the value by this line cmbCourses.Items.Add(a.Value);, Can you try this :

cmbCourses.Items.Add(item);

Then you can use this line to get the value :

MessageBox.Show(cmbCourses.SelectedValue.ToString());

Don't forget to set these for your combobox :

cmbCourses.DisplayMember = "YOUR DISPLAY FIELD NAME";
cmbCourses.ValueMember = "YOUR VALUE FIELD NAME";

Upvotes: 1

Leopold Stotch
Leopold Stotch

Reputation: 1522

You can use the GetValue() method to get the value rather than the display text:

MessageBox.Show(cmbCourses.GetValue().ToString());

Upvotes: 1

Related Questions