c#winform.net用户控件的创建按钮单击事件

c#winform.net用户控件的创建按钮单击事件,c#,winforms,button,events,user-controls,C#,Winforms,Button,Events,User Controls,我对c#winform(.net framework)用户控件有问题 我有一个“通知”用户控件,其中包含一个按钮和一些信息 我有一个“今日清单”表格,是用数据库生成的 我不知道如何为按钮创建事件。当我单击一个按钮时,我想从UC获取一个信息(标签) 图片: void UC_Click(object sender, EventArgs e) { //I gave an error for the below row! Can't conve

我对c#winform(.net framework)用户控件有问题

  • 我有一个“通知”用户控件,其中包含一个按钮和一些信息
  • 我有一个“今日清单”表格,是用数据库生成的
我不知道如何为按钮创建事件。当我单击一个按钮时,我想从UC获取一个信息(标签)

图片:

        void UC_Click(object sender, EventArgs e)
        {
            //I gave an error for the below row! Can't convert button type to notifications type i guess.
            notifications obj = (notifications)sender;
            MessageBox.Show(obj.Id);
        }
UC(我想获取“label2”文本)

生成的UCs

我试过这种方法,但没有成功:

        void UC_Click(object sender, EventArgs e)
        {
            //I gave an error for the below row! Can't convert button type to notifications type i guess.
            notifications obj = (notifications)sender;
            MessageBox.Show(obj.Id);
        }
编辑:

        void UC_Click(object sender, EventArgs e)
        {
            //I gave an error for the below row! Can't convert button type to notifications type i guess.
            notifications obj = (notifications)sender;
            MessageBox.Show(obj.Id);
        }
加州大学

谁能帮帮我吗

现在我得到一个错误:

        void UC_Click(object sender, EventArgs e)
        {
            //I gave an error for the below row! Can't convert button type to notifications type i guess.
            notifications obj = (notifications)sender;
            MessageBox.Show(obj.Id);
        }
通过定义自定义添加/删除访问器,可以将用户控件的事件“转发”到按钮:

// UC:
public event EventHandler ButtonClick
{
    add => btn.Click += value;
    remove => btn.Click -= value;
}
在主窗体中,您可以订阅
通知。单击
(这似乎是多个子项生成的用户控件)。但实际上,您应该订阅子控件的
按钮单击

((UC)asd.Controls[0]).ButtonClick += Child0Click;
你不需要

public event EventHandler btnClick;

试着把它取下来。

我不确定我是否明白这一点,但我看到你也是匈牙利人。你能帮我找个地方吗?我更新了我的答案,补充了遗漏的部分。我删除了这个错误:“System.InvalidCastException:”Az objektum nem konvertálható”System.Windows.Forms.Panel“típusról”Retask.Forms.notifications“típusra.”“我应该把你的第二个代码放在哪里?当然,从你的代码中我看不出你的控制有多深相互嵌入。但我希望意图是明确的。一个更优雅的解决方案是在
notifications
控件上创建一个
GetChild(int index)
方法,该方法在指定的索引处返回
UC
。如果生成动态,如何订阅主窗体中的按钮单击?我不知道我做错了什么,但实际上不起作用。我也这么做,链接中的内容和你写的内容。但当我点击按钮时,什么也不做。我用新代码更新了问题。我不知道我做错了什么,但现在它可以工作了。非常感谢你!