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?
When you set
ComboBox.SelectedIndex = -1theComboBox_SelectedIndexChangedfunction is called again as the index has been changed.When the function is called the second time,
NullReferenceExceptionis thrown asComboBox.SelectedValueis set tonullatSelectedIndexequal to-1.Solution: