获取一个组合框的选定值 [英] Getting selected value of a combobox

查看:137
本文介绍了获取一个组合框的选定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我加入他们喜欢的:

I'm adding them like:

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



我不断收到一个NullReferenceExeption,不知道为什么。 。文似乎显示了就好了。

I keep getting a NullReferenceExeption and not sure why. the text seems to show up just fine.

推荐答案

试试这个:

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

这篇关于获取一个组合框的选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆