为什么组合框的选定值不起作用
本文关键字:不起作用 组合 为什么 | 更新日期: 2023-09-27 18:08:10
我写了下面的代码,但它不能正常工作。如你所见,我定义了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.
}
}
如果您在使用SelectedItem
时获得NullRefernceException
,那么这意味着没有选择项目。确保选中了一个项目,并且SelectedItem
和SelectedValue
都可以工作。SelectedText
不是你想的那样。它的工作原理类似于TextBox
上具有相同名称的属性。你只需要Text
,而不是SelectedText
。
不太确定为什么NullReferenceException
会发生在您的selectedItem
上,但是下面的代码可以工作。由于某种原因,SelectedValue将为空,所以我只是将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; }
}
}