0

I am working on an ASP .Net C# project and I am a beginner in web programming. I get the below error at runtime:

Object reference not set to an instance of an object.

Below is my code:

protected void Page_Load(object sender, EventArgs e)
{
    txtUsername.Focus();
    if (cmbThemes.SelectedItem.Text=="Red")
    {
        pnlSignin.Border.BorderColor = Color.Orange;
    }
}

cmbThemes is a ComboBox.

Thanks in advance.

Rahul Krishnan R
  • 89
  • 2
  • 2
  • 6
  • 1
    When there is no item selected, `cmbThemes.SelectedItem` can be `null` and leads to the null exception – Tu Tran Nov 27 '13 at 06:53
  • Which line throws an exception? Are you sure that there is a `cmbThemes.SelectedItem` on `Page_Load()`? – Enam Nov 27 '13 at 06:53
  • 1
    Use a breakpoint on the first line. Then go step by step until the exception raises. You can always use your immediate window (in visual studio) to execute commands directly and find out which variable is null. I would guess that `cmbThemes` has no selected item... – Pantelis Natsiavas Nov 27 '13 at 06:54
  • after bind your dropdown you check – senthilkumar2185 Nov 27 '13 at 06:57
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – nvoigt Nov 27 '13 at 07:00
  • I am getting the error inside the if condition. pnlSignin is the panel i am using and getting the error there. – Rahul Krishnan R Nov 27 '13 at 07:30
  • pnlSignin.Border.BorderColor = Color.Orange; This line is throwing exception – Rahul Krishnan R Nov 27 '13 at 08:14

5 Answers5

7

change

if (cmbThemes.SelectedItem.Text=="Red")

to

if (cmbThemes.SelectedItem !=null &&cmbThemes.SelectedItem.Text=="Red")
{}
Ehsan
  • 31,833
  • 6
  • 56
  • 65
1

Check for values of your variables,one of your variable txtUsername or cmbThemes is NULL

Cris
  • 12,799
  • 5
  • 35
  • 50
0

Either set the default selectedindex of the combobox to something other than -1 or always check it SelectedItem == null before checking the text.

0

Is your combobox have any item yet? please make sure it has at least one item before you try to set or get any it's properties.

Ringo
  • 3,795
  • 3
  • 22
  • 37
0

You have to first check that your combobox must not be empty before check condition. You can do either:

protected void Page_Load(object sender, EventArgs e)
{
    txtUsername.Focus();
    if (cmbThemes.SelectedItem!=null)
    {
       if (cmbThemes.SelectedItem.Text=="Red")
       {
         //OtherOperations
       }
    }
 }

or

protected void Page_Load(object sender, EventArgs e)
{
   txtUsername.Focus();
   if (cmbThemes.SelectedIndex > -1)
   {
      if (cmbThemes.SelectedItem.Text=="Red")
      {
         //OtherOperations
      }
   }
}
Storm
  • 684
  • 9
  • 20