在 C# 中从父窗体为子窗体中的控件添加事件处理程序 [英] Adding an event handler for a control in child form from parent form in C#

查看:70
本文介绍了在 C# 中从父窗体为子窗体中的控件添加事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种形式.一种是带有按钮和文本框的父窗体.单击该按钮时,将打开一个对话框,该子窗体依次具有一个文本框和一个按钮.现在我想要的是每当子表单文本框中的文本更改父表单文本框中的文本时自动更改.为了获得这个,我所做的是:

I have two forms. One is a parent form with a button and a text box. On click of the button, a dialog opens the child form which in turn has a textbox and a button. Now what I want is whenever the text in the child form textbox changes the text in the parent form textbox changes automatically. To acquire this, what I did is:

Form3 f3 = new Form3();
f3.delBetInpTxt.TextChanged +=new EventHandler(delBetInpTxt_TextChanged);
public void delBetInpTxt_TextChanged(object sender, EventArgs e)
    {
        TextBox t = (TextBox)sender;
        simDelTxt.Text = t.Text + " ms";
    }

我在父窗体中添加了上面的代码,子窗体是Form3.但是没有任何反应,即使更改了子表单中的文本,父表单文本框仍然没有改变.我在这里做错了什么?

I added the above code in the parent form and the child form is Form3. But nothing happens, the parent form textbox still doesn't change even after changing the text in the child form. What am I doing wrong here?

推荐答案

您可以在子窗体中添加事件并在文本更改时将其提升.然后在父表单中创建事件处理程序并在父表单中更改文本.以儿童形式:

You can add event in child form and rise it when text changed. Then create event handler in parent form and change text in parent form. In child form:

public event EventHandler OnChildTextChanged;
private void textBox1_TextChanged(object sender, EventArgs e)
{
    if(OnChildTextChanged != null)
       OnChildTextChanged(textBox1.Text, null);
}

在父表单中:

private void button1_Click(object sender, EventArgs e)
{
    ChildForm child = new ChildForm();
    child.OnChildTextChanged += new EventHandler(child_OnChildTextChanged);
    child.ShowDialog();
}

void child_OnChildTextChanged(object sender, EventArgs e)
{
    textBox1.Text = (string)sender;
}

希望有帮助.

这篇关于在 C# 中从父窗体为子窗体中的控件添加事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆