日期:2014-05-18  浏览次数:20958 次

自定义控件里面的控件事件获取问题
有一个自定义控件
UserContr
里面有个ADD方法
public void Add(string name)
{
  picturebox pic = new picturebox();
  pic .name = name;
  pic.Click += picturebox_click;
}

public void picturebox_click(object sender,EventArgs e)
{
  string name = ((picturebox)sender).name;
}
还有一个Form窗体
里面加载这个自定义控件,我想在Form获取picturebox的Click事件,这个事件应该是自定义控件picturebox的共同的事件。
FormLoad()
{
  UserContr1.Add("1");
  UserContr1.Add("2");
  //我这样加就报错了
  UserContr1.picturebox_click +=picturebox_click;
}
public void picturebox_click(object sender,EventArgs e)
{
  string name = ((picturebox)sender).name;
}
提示是 picturebox_click 一个“方法组”, 无法为它赋值


------解决方案--------------------
你可以自定义事件啊
------解决方案--------------------
UserContr1.picturebox_click +=new System.EventHandler(picturebox_click);

------解决方案--------------------
C# code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class UserControl1 : UserControl
    {
        public event EventHandler PicClick;
        public UserControl1()
        {
            InitializeComponent();
        }
        
        public void Add(string name)
        {
            PictureBox pic = new PictureBox();
            pic.Name = name;
            pic.Parent = this;
            pic.Dock = DockStyle.Fill;
            pic.Click += picturebox_click;
        }
        public void picturebox_click(object sender, EventArgs e)
        {
            string name = ((PictureBox)sender).Name;
            if (PicClick != null)
            {
                PicClick(sender, e);
            }
        }
    }
}