2013-05-27 61 views
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」,有人能幫助我嗎?

+1

你可以檢查'SelectedValue'是否是'int' –

+0

@jacobaloysious這是一個'string'。 –

+0

看到這個http://stackoverflow.com/questions/6901070/getting-selected-value-of-a-combobox – Adil

回答

1

試試這個:

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

    int value = (int)comboBox2.SelectedValue; 
1

您正在將一個類themeS投射到int,這不起作用。

如果您希望themeS類中的Value屬性的值爲int

然後你可以檢索這樣說:如果你想使用SelectedValue您需要設置ValueMemberComboBox

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

Int32.TryParse

int currentItem = 0; 
    Int32.TryParse(((themeS)comboBox2.SelectedValue).Value, out  currentItem);