C#无法清除组合框的选定索引 [英] C# unable to clear combobox's selected index
问题描述
我有一个项目的组合框存储列表(不使用数据绑定),一个用于清除组合框和文本框的所有文本的按钮,带有几个文本框
当我按下清除按钮时,它会显示以下错误消息:
书签栏用户界面中发生未处理的System.NullReferenceException异常异常
附加信息:对象引用未设置为对象实例。
什么我试过了:
这是我的代码
我的按钮代码:< br $>
i got a combobox store list of item ( not using data bound ), a button used to clear all of the text of combobox and textbox, with a few textbox
when i press on the clear button, it show me this error message :
An unhandled exception of type 'System.NullReferenceException' occurred in bookbar user interface.exe
Additional information: Object reference not set to an instance of an object.
What I have tried:
this is my code
code for my button :
private void button1_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
comboBox1.SelectedIndex = -1;
}
i还在组合框中设置了一些代码,SelectedIndexChanged,这是错误信息显示的地方
i also set some code in the event of combobox, SelectedIndexChanged, this is where the error message show
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
if (comboBox1.SelectedItem.ToString() != "Lain-lain") { // < error in this line
textBox1.Clear();
}
else {
textBox1.Enabled = true;
}
updatebooknameList();
}
推荐答案
如果调试代码并在抛出异常的行上放置断点,您将发现comboBox1
的SelectedItem
属性为null
。
在发出.ToString()
If you debug your code and put a breakpoint on the line where the exception is thrown, you will discover that theSelectedItem
property ofcomboBox1
isnull
.
You need to check for it being null before you issue the.ToString()
这篇关于C#无法清除组合框的选定索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!