C#添加目标代码错误 [英] C# adding object code error

查看:92
本文介绍了C#添加目标代码错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码

This is my code

// 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

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




这就是错误所在

Object reference not set to an instance of an object.

我正在尝试单击它,如果选择了这些或未选择任何东西,则什么也不会发生.




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

推荐答案

您需要先进行测试:
You need to test first:
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

label = new Label();

在发生这种情况的方法中.

inside the method for that to happen.


这篇关于C#添加目标代码错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆