Search code examples
c#winformscombobox

Retrieve Value/Name of selected item of comboBox


I'm working on a winforms application, I have a comboBox that I bind from a database, each item have a Name and a Value:

 // New item class
 public class themeS
 {
     public string Name { get; set; }
     public string Value { get; set; }
     public override string ToString() { return this.Name; }
 }

 // Binding ComboBox Event
 using (DbEntities db = new DbEntities())
 {
    comboBox2.Items.Clear();
    IEnumerable tem  = from t in db.Themes where t.idCategorie == 1  select t;
    foreach (Themes Tem in tem)
    {
        comboBox2.Items.Add(new themeS { Value = Tem.idTheme.ToString(), Name= Tem.nomTheme });
    }
 }

Now I want to retrieve the Value of selected item of combobox:

string curentIdTem = comboBox2.SelectedValue.ToString();

The returned value of comboBox2.SelectedValue is always 'NULL', can someone help please?


Solution

  • Try this:

    int curentIdTem =  Convert.ToInt32(((themeS)comboBox2.SelectedItem).Value);