如何在c#winform中单击某个组件时获得用户控件本身
本文关键字:用户 控件 组件 c#winform 单击 | 更新日期: 2023-09-27 18:24:14
我制作了一个用户控件,并在主窗体中为其中的一个面板添加了一个点击事件。我想获得用户控件,这样我就可以在其中使用其他东西,但发送者将是一个面板,而不是用户控件。这就是我的
void panel1_Click(object sender, EventArgs e)
{
Panel p = (Panel)(sender);
//UserControl1 tmp = ....
label1.Text = "Item Code:" + tmp.pro.product_code;
label2.Text = "Name:" + tmp.pro.product_name;
label3.Text = "Price:" + tmp.pro.product_price;
}
我该怎么做?感谢
我不太确定我是否读对了这篇文章,但从你所说的,我认为你在主窗体上有一个面板和一个用户控件,你想用用户控件的值更新主窗体上的面板。如果这是正确的,那么尝试这个
方法1:
void panel1_Click(object sender, EventArgs e)
{
Panel p = (Panel)(sender);
UserControl tmp;
foreach (Control control in MainForm.Controls)
{
if (control is UserControl)
{
if (control.Name == "MyUserControlName")
{
tmp = control as UserControl;
}
}
}
//Let's check that we got the control
if (tmp != null)
{
//Now find the controls / Variables that are holding your values in the user control first - I'm assuming textboxes
TextBox txtProductCode = tmp.Controls.Find("TextBox1",false);
TextBox txtProductName = tmp.Controls.Find("TextBox2",false);
TextBox txtProductPrice = tmp.Controls.Find("TextBox3",false);
label1.Text = "Item Code:" + txtProductCode.Text;
label2.Text = "Name:" + txtProductName.Text;
label3.Text = "Price:" + txtProductPrice.Text;
}
}
方法2:
除了删除foreach循环并替换以下之外,所有内容都与方法一相同
UserControl tmp;
foreach (Control control in MainForm.Controls)
{
if (control is UserControl)
{
if (control.Name == "MyUserControlName")
{
tmp = control as UserControl;
}
}
}
用这个
var tmp = MainFForm.Controls.Find("MyUserControlName",false);
其中"MainForm"是放置用户控件的主窗体的名称,"MyUserControlName"是用户控件的名称