2011-08-01 36 views
28
public class ComboboxItem { 
      public string Text { get; set; } 
      public string Value { get; set; } 
      public override string ToString() { return Text; } 
     } 

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
     { 
      int selectedIndex = comboBox1.SelectedIndex; 
      int selecteVal = (int)comboBox1.SelectedValue; 
      ComboboxItem selectedCar = (ComboboxItem)comboBox1.SelectedItem; 
      MessageBox.Show(String.Format("Index: [{0}] CarName={1}; Value={2}", selectedIndex, selectedCar.Text, selecteVal)); 
     } 

我加入他們喜歡的值:獲得選擇的組合框

ComboboxItem item = new ComboboxItem(); 
        item.Text = cd.Name; 
        item.Value = cd.ID; 
        this.comboBox1.Items.Add(item); 

我不斷收到一個NullReferenceExeption,不知道爲什麼。文本似乎顯示得很好。

回答

31

試試這個:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    ComboBox cmb = (ComboBox)sender; 
    int selectedIndex = cmb.SelectedIndex; 
    int selectedValue = (int)cmb.SelectedValue; 

    ComboboxItem selectedCar = (ComboboxItem)cmb.SelectedItem; 
    MessageBox.Show(String.Format("Index: [{0}] CarName={1}; Value={2}", selectedIndex, selectedCar.Text, selecteVal));   
} 
+6

我認爲'ComboBoxItem'類只在WPF項目中可用。 – T30

13

您使用的是cmb.SelectedValue是空越來越NullReferenceExeption因爲你。該comboBox不知道什麼是你的自定義類ComboboxItem的價值,因此無論是做:

ComboboxItem selectedCar = (ComboboxItem)comboBox2.SelectedItem; 
int selecteVal = Convert.ToInt32(selectedCar.Value); 

或更好的結合使用數據,如:

ComboboxItem item1 = new ComboboxItem(); 
item1.Text = "test"; 
item1.Value = "123"; 

ComboboxItem item2 = new ComboboxItem(); 
item2.Text = "test2"; 
item2.Value = "456"; 

List<ComboboxItem> items = new List<ComboboxItem> { item1, item2 }; 

this.comboBox1.DataSource = items; 
this.comboBox1.DisplayMember = "Text"; 
this.comboBox1.ValueMember = "Value"; 
+0

反正沒有使用comboBox.SelectedValue自定義項目而不使用數據源?例如。如果使用數據源,則無法刪除項目或將項目添加到組合框項目。 – user3532232

6

我有一個類似的錯誤,我類是

public class ServerInfo 
{ 
    public string Text { get; set; } 
    public string Value { get; set; } 
    public string PortNo { get; set; } 

    public override string ToString() 
    { 
     return Text; 
    } 
} 

但是我做了什麼,我把我的類鑄造成ComboBox的SelectedItem屬性。所以,我將擁有所選項目的所有類屬性。

// Code above 
ServerInfo emailServer = (ServerInfo)cbServerName.SelectedItem; 

mailClient.ServerName = emailServer.Value; 
mailClient.ServerPort = emailServer.PortNo; 

我希望這可以幫助別人! 乾杯!

-1

試試這個:

private void cmbLineColor_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     DataRowView drv = (DataRowView)cmbLineColor.SelectedItem; 
     int selectedValue = (int)drv.Row.ItemArray[1]; 
    } 
0

你與SelectedValue問題不轉換爲整數。這是主要的問題,所以使用下面的代碼片段將幫助你:

int selectedValue; 
bool parseOK = Int32.TryParse(cmb.SelectedValue.ToString(), out selectedValue);