我在下面写了代码,但它无法正常工作。如您所见,我定义了ValueMember
和DisplayMember
。但是,对于所有项目,它都不显示SelectedItem
或SelectedValue
,要么我选择Selectable
项目。
private class ComboBoxItem
{
public int Value { get; set; }
public string Text { get; set; }
public bool Selectable { get; set; }
}
private void Form1_Load(object sender, EventArgs e)
{
this._cmb.ValueMember = "Value";
this._cmb.DisplayMember = "Text";
this._cmb.Items.AddRange(new[] {
new ComboBoxItem() { Selectable = false, Text="Unselectable", Value=0},
new ComboBoxItem() { Selectable = true, Text="Selectable1", Value=1},
new ComboBoxItem() { Selectable = true, Text="Selectable2", Value=2},
});
this._cmb.SelectedIndexChanged += (cbSender, cbe) =>
{
var cb = cbSender as ComboBox;
if (cb.SelectedItem != null && cb.SelectedItem is ComboBoxItem && ((ComboBoxItem)cb.SelectedItem).Selectable == false)
{
// deselect item
cb.SelectedIndex = -1;
}
};
private void button1_Click(object sender, EventArgs e)
{
label.Text = _cmb.SelectedItem.ToString(); // it says Object reference not set to an instance of an object.
label.Text = _cmb.SelectedText.ToString(); // it returns ""
label.Text = _cmb.SelectedValue.ToString(); // it says Object reference not set to an instance of an object.
}
}
答案 0 :(得分:0)
如果您在使用NullRefernceException
时获得SelectedItem
,则表示未选择任何项目。确保选中了一个项目,SelectedItem
和SelectedValue
都可以使用。 SelectedText
不是你想的那样。它的作用类似于TextBox
上具有相同名称的属性。您只需要Text
,而不是SelectedText
。
答案 1 :(得分:0)
不完全确定为NullReferenceException
发生了selectedItem
为什么,但以下代码可以正常运行。由于某种原因,SelectedValue将为null,因此我只是将SelectedItem
转换回ComboBoxItem
类型,然后可以访问其所有属性
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//label.Text = _cmb.SelectedItem.ToString(); // it says Object reference not set to an instance of an object.
//label.Text += _cmb.SelectedText.ToString(); // it returns ""
//label.Text += _cmb.SelectedValue.ToString(); // it says Object reference not set to an instance of an object.
ComboBoxItem item = (ComboBoxItem) this._cmb.SelectedItem;
if (item != null)
{
label.Text = item.Value.ToString();
label.Text += item.Text;
}
}
private void Form1_Load(object sender, EventArgs e)
{
this._cmb.ValueMember = "Value";
this._cmb.DisplayMember = "Text";
this._cmb.Items.AddRange(new[] {
new ComboBoxItem() { Selectable = false, Text="Unselectable", Value=0},
new ComboBoxItem() { Selectable = true, Text="Selectable1", Value=1},
new ComboBoxItem() { Selectable = true, Text="Selectable2", Value=2},
});
this._cmb.SelectedIndexChanged += (cbSender, cbe) =>
{
var cb = cbSender as ComboBox;
if (cb.SelectedItem != null && cb.SelectedItem is ComboBoxItem && ((ComboBoxItem)cb.SelectedItem).Selectable == false)
{
// deselect item
cb.SelectedIndex = -1;
}
};
}
}
public class ComboBoxItem
{
public int Value { get; set; }
public string Text { get; set; }
public bool Selectable { get; set; }
}
}