我有两种形式。一个是带有按钮和文本框的父表单。单击该按钮时,将打开一个对话框,打开子窗体,该子窗体又具有一个文本框和一个按钮。现在我想要的是,只要子表单文本框中的文本发生更改,父表单文本框中的文本就会自动更改。为了获得这个,我所做的是:
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。但是没有任何反应,即使在更改子表单中的文本后,父表单文本框仍然没有更改。我在这里做错了什么?
最佳答案
您可以在子窗体中添加事件,并在文本更改时将其升起。然后在父窗体中创建事件处理程序并更改父窗体中的文本。 以子形式:
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# - 在 C# 中从父窗体添加子窗体控件的事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6382750/