Search code examples
c#.netvisual-studiocomboboxdatabound

nullpointer when setting combobox index to -1


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?


Solution

  • When you set ComboBox.SelectedIndex = -1 the ComboBox_SelectedIndexChanged function is called again as the index has been changed.

    When the function is called the second time, NullReferenceException is thrown as ComboBox.SelectedValue is set to null at SelectedIndex equal to -1.

    Solution:

    private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        if(ComboBox.SelectedIndex != -1)
        {
            MainTextBox.Text = ComboBox.SelectedValue.ToString();
            ComboBox.SelectedIndex = -1;
        }
    }