Reputation: 89
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.
Upvotes: 0
Views: 1944
Reputation: 13341
Check for values of your variables,one of your variable
txtUsername
or cmbThemes
is NULL
Upvotes: 1
Reputation: 1
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
}
}
}
Upvotes: 0
Reputation: 3965
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.
Upvotes: 0
Reputation: 171
Either set the default selectedindex of the combobox to something other than -1 or always check it SelectedItem == null before checking the text.
Upvotes: 0
Reputation: 32661
change
if (cmbThemes.SelectedItem.Text=="Red")
to
if (cmbThemes.SelectedItem !=null &&cmbThemes.SelectedItem.Text=="Red")
{}
Upvotes: 7