获得组合框的选定值

max*_*axy 35 c# combobox selectedvalue selectedindexchanged selecteditem

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));
        }
Run Code Online (Sandbox Code Playgroud)

我正在添加它们:

ComboboxItem item = new ComboboxItem();
                    item.Text = cd.Name;
                    item.Value = cd.ID;
                    this.comboBox1.Items.Add(item);
Run Code Online (Sandbox Code Playgroud)

我一直得到一个NullReferenceExeption,不知道为什么.文本似乎显示得很好.

Jam*_*ill 40

试试这个:

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));        
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为`ComboBoxItem`类仅在WPF项目中可用. (6认同)

Jal*_*aid 13

你得到的NullReferenceExeption是因为你使用的cmb.SelectedValue是null.在comboBox不知道什么是你的自定义类的值ComboboxItem,所以无论做:

ComboboxItem selectedCar = (ComboboxItem)comboBox2.SelectedItem;
int selecteVal = Convert.ToInt32(selectedCar.Value);
Run Code Online (Sandbox Code Playgroud)

或者更好的是使用数据绑定,如:

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.DisplayMember = "Text";
this.comboBox1.ValueMember = "Value";
this.comboBox1.DataSource = items;
Run Code Online (Sandbox Code Playgroud)


小智 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我做了什么,我将我的类转换为ComboBox的SelectedItem属性.所以,我将拥有所选项目的所有类属性.

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

mailClient.ServerName = emailServer.Value;
mailClient.ServerPort = emailServer.PortNo;
Run Code Online (Sandbox Code Playgroud)

我希望这可以帮助别人!干杯!