在自定义控件里,写了两个label,想在usercotrol获得焦点的时候加亮第一个label。
 我写的这样:
  public partial class UserControl1 : UserControl
    {
        Label label1,label2;
        UserControl1 abc;
        public UserControl1()
        {
            InitializeComponent();
        }        private void UserControl1_Load(object sender, EventArgs e)
        {
            label1 = new Label();
            label2 = new Label();
            abc = new UserControl1();
            this.Controls.Add(label1);
            this.Controls.Add(label1);
            abc.GotFocus += new EventHandler(this.abc_GotFocus);
        }
        private void abc_GotFocus(object sender, EventArgs e)
        {
            label1.BackColor = Color.Blue;
        }
    }这样为什么不可以?

解决方案 »

  1.   

    abc = new UserControl1(); //你是new的UserControl1,而不是当前的UserControl1
    代码改成这样        private void UserControl1_Load(object sender, EventArgs e)
            {
                label1 = new Label();
                label2 = new Label();
                
                this.Controls.Add(label1);
                this.Controls.Add(label1);
                this.GotFocus += new EventHandler(this.abc_GotFocus);
            } 
      

  2.   

    或者        private void UserControl1_Load(object sender, EventArgs e)
            {
                label1 = new Label();
                label2 = new Label();
                abc = this;
                this.Controls.Add(label1);
                this.Controls.Add(label1);
                abc.GotFocus += new EventHandler(this.abc_GotFocus);
            }