获取组合框的选定值
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);
我不断收到 NullReferenceException,但不知道为什么。文字似乎显示得很好。
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);
I keep getting a NullReferenceExeption and not sure why. the text seems to show up just fine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
试试这个:
Try this:
您收到
NullReferenceExeption
是因为您使用的cmb.SelectedValue
为 null。comboBox
不知道自定义类ComboboxItem
的值是什么,所以要么这样做:或者更好的是使用数据绑定,例如:
You are getting
NullReferenceExeption
because of you are using thecmb.SelectedValue
which is null. thecomboBox
doesn't know what is the value of your custom classComboboxItem
, so either do:Or better of is use data binding like:
我有一个类似的错误,我的类是
但是我所做的,我将我的类转换为 ComboBox 的 SelectedItem 属性。因此,我将拥有所选项目的所有类属性。
我希望这对某人有帮助!
干杯!
I had a similar error, My Class is
But what I did, I casted my class to the SelectedItem property of the ComboBox. So, i'll have all of the class properties of the selected item.
I hope this helps someone!
Cheers!
您必须将所选项目转换为自定义类(ComboboxItem)
试试这个:
}
You have to cast the selected item to your custom class (ComboboxItem)
Try this:
}
试试这个:
Try this:
SelectedValue
遇到的问题不是转换为整数。这是主要问题,因此使用以下代码片段将帮助您:The problem you have with the
SelectedValue
is not converting into integer. This is the main problem so usinge the following code snippet will help you:试试这个:
Try this:
我找到了一种将组合框值转换为自定义类型的方法,
如果你这样做,代码仍然是 IntelliSense(代码建议已启用)
当你想要设置值时
当你想要取回自定义类型(你自己的类)的值时
I found a way to cast combobox value to a custom type,
if you do like this the code is still IntelliSense(code suggestion is enable)
When you want to set values
When you want to get back value of a custom type(your own class)