1

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?

Naourass Derouichi
  • 773
  • 3
  • 12
  • 38

3 Answers3

1

You are casting a class themeS to an int which would not work.

If you are expecting an int value in the Value property in themeS class.

Then you could retrieve it this way: Int32.TryParse

    int currentItem = 0;
    Int32.TryParse(((themeS)comboBox2.SelectedValue).Value, out     currentItem);
jacob aloysious
  • 2,547
  • 15
  • 16
1

Try this:

int curentIdTem =  Convert.ToInt32(((themeS)comboBox2.SelectedItem).Value);
dotINSolution
  • 224
  • 1
  • 5
1

If you want to use SelectedValue you need to set the ValueMember on the ComboBox

Example:

   comboBox1.ValueMember = "Value";
   .....

   int value = (int)comboBox2.SelectedValue;
sa_ddam213
  • 42,848
  • 7
  • 101
  • 110