Reputation: 793
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?
Upvotes: 1
Views: 13976
Reputation: 43636
If you want to use SelectedValue
you need to set the ValueMember
on the ComboBox
Example:
comboBox1.ValueMember = "Value";
.....
int value = (int)comboBox2.SelectedValue;
Upvotes: 1
Reputation: 234
Try this:
int curentIdTem = Convert.ToInt32(((themeS)comboBox2.SelectedItem).Value);
Upvotes: 1
Reputation: 2597
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);
Upvotes: 1