C# 如何使用usercontrol更新表单中的标签文本?
我将一个按钮放在UserControl中,并将这个UserControl放在表单中。 我希望在单击按钮时更新表单中的文本框文本C# 如何使用usercontrol更新表单中的标签文本?,c#,winforms,user-controls,C#,Winforms,User Controls,我将一个按钮放在UserControl中,并将这个UserControl放在表单中。 我希望在单击按钮时更新表单中的文本框文本 public partial class UserControl1 : UserControl { public UserControl1() { InitializeComponent(); } private void button1_Click(object sende
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1 form1 = new Form1();
form1.textBox1.Text = "1";
//The textbox text is not updated!
}
}
文本框文本未更新删除创建新表单的行
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "1";
//The textbox text is not updated!
}
}
不要创建新表单。请移开那条线 我猜您正在尝试为表单中的文本框设置文本,而您的按钮位于Usercontrol中,它是表单的子组件 如果是这样,请从窗体注册EventHandler,并从UserControl中的按钮触发事件 在UserControl中注册EventHandler:
public event EventHandler ButtonClicked;
protected virtual void OnButtonClicked(EventArgs e)
{
var handler = ButtonClicked;
if (handler != null)
handler(this, e);
}
private void Button_Click(object sender, EventArgs e)
{
OnButtonClicked(e);
}
this.userControl1.ButtonClicked += userControl11_ButtonClicked;
private void userControl11_ButtonClicked(object sender, EventArgs e)
{
this.TextBox1.Text = "1";
}
在表单中,您可以从UserControl订阅事件:
public event EventHandler ButtonClicked;
protected virtual void OnButtonClicked(EventArgs e)
{
var handler = ButtonClicked;
if (handler != null)
handler(this, e);
}
private void Button_Click(object sender, EventArgs e)
{
OnButtonClicked(e);
}
this.userControl1.ButtonClicked += userControl11_ButtonClicked;
private void userControl11_ButtonClicked(object sender, EventArgs e)
{
this.TextBox1.Text = "1";
}
告诉我您的结果。您正在创建一个新的
表单1
。你没有表现出来。您可能打算更新现有的表单1
。我假设UserControl1
放在Form1
上。然后你可以这样做:
private void按钮1\u单击(对象发送者,事件参数e)
{
//获取父窗体
Form1 myForm=(Form1)this.parent;
myForm.TextBox1.Text=“1”;
}
如果您的
UserControl1
不在Form1
上,那么您需要以某种方式传递一个引用。您正在创建一个新的Form1。你没有表现出来。您可能想更新现有表单1。是的,我想更新表单-我不想打开新表单。我该怎么办?@mehrannosrati我更新了答案。请查看。当前文件中不存在名称“TextBox1”context@mehrannosrati对不起,我迟了答复。如果您尚未修复此问题,请创建一个带有此问题的github项目,我将尽力帮助您。错误='UserControl1'不包含的定义,并且找不到接受类型为'UserControl1'的第一个参数的可访问扩展方法(您是否缺少using指令或程序集引用?)这与我添加的行无关。一定是出了什么问题。“UserControl1”不包含父对象的定义,并且在按钮中找不到接受“UserControl1”类型的第一个参数的可访问扩展方法父对象。\u单击此
引用了UserControl1
的实例。它没有TextBox1成员。啊,所以TextBox在UserControl中,而不是FormNo中,TextBox在form中,按钮在UserControl中。请参阅参考以在子组件中引发事件并在父组件中订阅:不客气。如果您觉得这有帮助,请您投票并标记此答案。非常感谢。