2011-08-01 34 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);