【问题标题】:Adding an event handler for a control in child form from parent form in C#在 C# 中从父窗体为子窗体中的控件添加事件处理程序
【发布时间】:2019-07-26 05:47:54
【问题描述】:

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

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。但是什么也没有发生,即使更改了子表单中的文本,父表单文本框仍然没有改变。我在这里做错了什么?

【问题讨论】:

  • 您是否调试过应用程序,看看 sender 是否不为 null 以及 Text 属性是否也一样?

标签: c# winforms inheritance


【解决方案1】:

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

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

希望对你有帮助。

【讨论】:

  • 通过交换实现,我能够单击父窗体上的菜单按钮并启用用户控件上的按钮。所以谢谢你的回答
  • 这给了我错误。 “Form”不包含“OnFilterQueryGenerated”的定义,并且找不到接受“Form”类型的第一个参数的扩展方法“OnFilterQueryGenerated”(您是否缺少 using 指令或程序集引用?)。我完全按照你的做法做了。
  • @Huzaifa99 在我的示例中,没有 Form 类用户,也没有名为 OnFilterQueryGenerated 的方法。为了帮助您,您需要展示您的代码。
猜你喜欢
  • 2016-11-02
  • 1970-01-01
  • 1970-01-01
  • 2015-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-26
相关资源
最近更新 更多