Click here to Skip to main content
15,887,854 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
This is my code

C#
// this creates a new label every times panel1 is clicked
 Label label = new Label();
 private void panel1_Click(object sender, EventArgs e)
 {

     if ((treeView1.SelectedNode.Text == "Instruments") || (treeView1.SelectedNode.Text == "Drums") || (treeView1.SelectedNode.Text == "Pre-Made Beats") || (treeView1.SelectedNode.Text == "") )
     {
     }
     else
     {
         label.Visible = true;
         label.Location = new Point(lastClicked.X, 10);
         label.Text = treeView1.SelectedNode.Text;
         panel1.Controls.Add(label);
     }

     }


This is where my error is

SQL
if ((treeView1.SelectedNode.Text == "Instruments") || (treeView1.SelectedNode.Text == "Drums") || (treeView1.SelectedNode.Text == "Pre-Made Beats") || (treeView1.SelectedNode.Text == "") )
    {
    }



this is what the error is

Object reference not set to an instance of an object.

I'm trying so when it is clicked that nothing will happen if those are selected or nothing is selected
Posted

1 solution

You need to test first:
C#
private void panel1_Click(object sender, EventArgs e)
   {
   if (treeView1.SelectedNode != null)
      {
      ...
      }
   }
In addition, that does not add a new label each time the panel is clicked - you need to put the
C#
label = new Label();
inside the method for that to happen.
 
Share this answer
 
Comments
[no name] 11-Apr-12 5:48am    
the null code didn't work
OriginalGriff 11-Apr-12 6:19am    
What do you mean by "didn't work" - was there an error?
[no name] 11-Apr-12 6:20am    
yes there was still the same error
OriginalGriff 11-Apr-12 6:23am    
Can you paste the exact code, and indicate where it gave the null reference?
[no name] 11-Apr-12 20:25pm    
private void panel1_Click(object sender, EventArgs e)
{

if ((treeView1.SelectedNode.Text == "Instruments") ||
(treeView1.SelectedNode.Text == "Drums") ||
(treeView1.SelectedNode.Text == "Pre-Made Beats") || (treeView1.SelectedNode != null))
{

}
else
{
Label label = new Label();
label.Visible = true;
label.Location = new Point(lastClicked.X, 10);
label.Text = treeView1.SelectedNode.Text;
panel1.Controls.Add(label);
}

}
and got the error in the if statement

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900