-2

I make richtextbox disable by choosing "cleared" on a combobox, and I get this error "object reference set to an instance of an object"

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        if (comboBox1.SelectedItem.ToString() == "Cleared")
        {
            richTextBox1.Enabled = false;
            richTextBox1.Text = "";
        }
        else
        {
            richTextBox1.Enabled = true;
        }
    }
    catch (Exception a)
    {
        MessageBox.Show(a.Message);
    }
}
D Stanley
  • 149,601
  • 11
  • 178
  • 240

2 Answers2

1

try:

if (comboBox1.SelectedItem != null && comboBox1.SelectedItem.ToString() == "Cleared")
JBrooks
  • 9,901
  • 2
  • 28
  • 32
0

Since it seems unlikely that richTextBox1 is null (since it's probably given a value as initialization), the only other possibility is that comboBox1.SelectedItem is null. The simplest fix would be to check for null:

    if (comboBox1.SelectedItem != null && comboBox1.SelectedItem.ToString() == "Cleared")
    {
        richTextBox1.Enabled = false;
        richTextBox1.Text = "";
    }
D Stanley
  • 149,601
  • 11
  • 178
  • 240