0

我有一个来自用户控件的按钮,并希望它在单击时通知我的表单。这是我的做法。这没用。有人可以告诉我它有什么问题吗?

在用户控制中

    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");
    }

谢谢

4

1 回答 1

2

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

尝试clicked += new EventHandler(Add_Click);从您的 UserControl 中删除并将UserControls Button Click事件设置为,以便它会在您身上Add_Click触发clickedForm

例子:

用户控制:

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)
    {

    }
}
于 2013-03-05T07:49:10.860 回答