I have a combobox that gets it data from a database table.
我有一个组合框从数据库表中获取数据。
When Selected index changes I want to send the value of the selection to a textbox and then clear the selection.
选择索引更改时,我想将选择的值发送到文本框,然后清除选择。
private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
MainTextBox.Text = ComboBox.SelectedValue.ToString();
ComboBox.SelectedIndex = -1;
}
This gets the data to the textbox and clears the combobox, but also gives a null pointer exception.
这会将数据传输到文本框并清除组合框,但也会产生空指针异常。
This line by itself works fine:
这条线本身很好用:
MainTextBox.Text = ComboBox.SelectedValue.ToString();
This line by itself works fine:
这条线本身很好用:
ComboBox.SelectedIndex = -1;
How do I solve this?
我该如何解决这个问题?
1 个解决方案
#1
3
When you set ComboBox.SelectedIndex = -1
the ComboBox_SelectedIndexChanged
function is called again as the index has been changed.
设置ComboBox.SelectedIndex = -1时,随着索引的更改,将再次调用ComboBox_SelectedIndexChanged函数。
When the function is called the second time, NullReferenceException
is thrown as ComboBox.SelectedValue
is set to null
at SelectedIndex
equal to -1
.
当第二次调用该函数时,抛出NullReferenceException,因为在SelectedIndex中ComboBox.SelectedValue设置为null,等于-1。
Solution:
解:
private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if(ComboBox.SelectedIndex != -1)
{
MainTextBox.Text = ComboBox.SelectedValue.ToString();
ComboBox.SelectedIndex = -1;
}
}
#1
3
When you set ComboBox.SelectedIndex = -1
the ComboBox_SelectedIndexChanged
function is called again as the index has been changed.
设置ComboBox.SelectedIndex = -1时,随着索引的更改,将再次调用ComboBox_SelectedIndexChanged函数。
When the function is called the second time, NullReferenceException
is thrown as ComboBox.SelectedValue
is set to null
at SelectedIndex
equal to -1
.
当第二次调用该函数时,抛出NullReferenceException,因为在SelectedIndex中ComboBox.SelectedValue设置为null,等于-1。
Solution:
解:
private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if(ComboBox.SelectedIndex != -1)
{
MainTextBox.Text = ComboBox.SelectedValue.ToString();
ComboBox.SelectedIndex = -1;
}
}