如何使用用户控件更新表单中的标签文本?

How to update the label text in the form with usercontrol?

我在 UserControl 里面放了一个按钮,然后把这个 UserControl 放到窗体里。 我希望在单击按钮时更新表单中的文本框文本。

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!
            }
        }

不要创建新表单。请删除该行。

我猜您正在尝试为 Form 中的 TextBox 设置文本,而您的按钮位于 Usercontrol 中,它是 Form 的子组件。

如果是这样,请从您的表单注册一个事件处理程序,并从您的用户控件中的按钮触发事件。

在您的用户控件中注册一个事件处理程序:

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

在您的表单中,您订阅了来自 UserControl 的事件:

this.userControl1.ButtonClicked += userControl11_ButtonClicked;

private void userControl11_ButtonClicked(object sender, EventArgs e)
{
    this.TextBox1.Text = "1";
}

告诉我你的结果。

您正在创建一个新的 Form1。你没有表现出来。您可能打算更新现有的 Form1。我想 UserControl1 放在 Form1 上。那么你可以这样做:

private void button1_Click(object sender, EventArgs e)
{
    // Get the parent form
    Form1 myForm = (Form1) this.parent;
    myForm.TextBox1.Text = "1";
}

如果您的 UserControl1 不在 Form1 上,那么您需要以某种方式传递引用。