1

我正在开发一个 winforms 应用程序,我有一个从数据库绑定的组合框,每个项目都有一个名称和一个值:

 //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 });
    }
 }

现在我想检索组合框选定项的值:

string curentIdTem = comboBox2.SelectedValue.ToString();

的返回值comboBox2.SelectedValue始终为 'NULL' ,有人可以帮我吗?

4

3 回答 3

1

您正在将一个类themeS转换为一个int不起作用的类。

如果您期望类中的属性int值。ValuethemeS

然后你可以这样检索它:Int32.TryParse

    int currentItem = 0;
    Int32.TryParse(((themeS)comboBox2.SelectedValue).Value, out     currentItem);
于 2013-05-27T04:29:56.770 回答
1

尝试这个:

int curentIdTem =  Convert.ToInt32(((themeS)comboBox2.SelectedItem).Value);
于 2013-05-27T04:31:02.710 回答
1

如果你想使用SelectedValue你需要设置ValueMemberComboBox

例子:

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

   int value = (int)comboBox2.SelectedValue;
于 2013-05-27T04:39:12.350 回答