当用户控件's按钮被点击时,eventandler不会触发

本文关键字:eventandler 控件 用户 按钮 | 更新日期: 2023-09-27 18:02:21

我有一个来自用户控件的按钮,并希望它在单击时通知我的表单。我是这样做的。这行不通。谁能告诉我有什么问题吗?

用户控制

    public event EventHandler clicked;
    public string items;
    InitializedData data = new InitializedData();
    ArrayList list = new ArrayList();
    public DataInput()
    {
        InitializeComponent();
        clicked+= new EventHandler(Add_Click);
    }

    public void Add_Click(object sender, EventArgs e)
    {
        items = textBox1.Text.PadRight(15) + textBox2.Text.PadRight(15) + textBox3.Text.PadRight(15);
        if (clicked != null)
        {
            clicked(this, e);
        }
    }
在Form1

    UserControl dataInput= new UserControl();
    public void OnChanged(){
        dataInput.clicked += Notify;
        MessageBox.Show("testing");
    }
    public void Notify(Object sender, EventArgs e)
    {
        MessageBox.Show("FIRE");
    }

谢谢

当用户控件's按钮被点击时,eventandler不会触发

UserControls Button Click事件应该分配给Add_Click,我认为您不应该将UserControl clicked事件分配给Add_Click

尝试从您的UserControl中删除clicked += new EventHandler(Add_Click);,并将UserControls Button Click事件设置为Add_Click,因此它将触发clicked在您的Form

的例子:

用户控件:

public partial class UserControl1 : UserControl
{
    public event EventHandler clicked;
    public UserControl1()
    {
        InitializeComponent();
        // your button
        this.button1.Click += new System.EventHandler(this.Add_Click);
    }
    public void Add_Click(object sender, EventArgs e)
    {
        if (clicked != null)
        {
           // This will fire the click event to anyone listening
            clicked(this, e);
        }
    }
}

形式:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        // your usercontrol
        userControl11.clicked += userControl11_clicked;
    }
    void userControl11_clicked(object sender, EventArgs e)
    {
    }
}