【问题标题】:Controls do not change color or text, when I call method from another form当我从另一个表单调用方法时,控件不会更改颜色或文本
【发布时间】:2018-09-10 08:48:49
【问题描述】:

注意:Form2 是 MDI 子窗体,我将 Form1 的所有修饰符设置为 Public

当我想更改颜色或文本等时,我的方法不起作用... 例如:有两种形式,Form1 和 Form2。在 Form2: label1.Click 事件中我这样做了:

在 Form2 中:

private void label1_MouseClick(object sender, MouseEventArgs e)
    {
        Form1 f1 = new Form1();
        Label name = ((Label)sender);
        f1.getInfoLabel(name);
    }

好的,直到这里一切正常,但在那里:

在表格 1 中:

public void getInfoLabel(Label obj)
    {
        pictureBox1.BackColor = obj.Forecolor; //not working
        TextBox1.Text = obj.Text; //not working
        MessageBox.Show(obj.Forecolor.ToString()); //working
        MessageBox.Show(obj.Text); //working
    }

有什么帮助吗?请。

【问题讨论】:

  • 您正在创建Form1 实例。您是否打算与Form1现有 实例进行交互?如果是这样,您需要通过其他方式安排这种情况发生。例如。如果Form2 是由Form1 创建的,也许您需要将Form1 设为Form2 的父级,或者在构造函数参数或属性中显式传递它。
  • 您是否有机会创建 Form1 的两个(或更多)副本,而不是对已经存在的副本采取行动? Form f1 = new Form() 将创建一个新的(可能是不可见的)Form1 实例。如果此表单已在您的屏幕上打开,您需要针对对该表单的引用执行代码,而不是创建它的新副本
  • @Damien_The_Unbeliever 我在 MDIParent 上工作,Form2 是 Form1 的子表单,就像 Visual Studio Designer 一样。我认为它来自MDI。也许?

标签: c# winforms mdi


【解决方案1】:

而不是

Form1 f1 = new Form1();

使用

Form1 f1 = this.MDIParent as Form1;
if (f1 != null)
{
    f1.getinfolabel(sender as Label);
}

正如已经指出的那样,您正在创建一个新的 Form1 实例并与之交互,而不是与父窗体交互。只要您正确设置了 Form2 的 MDIParent,那么上面的方法应该可以工作。

另一种方法是使用:

Form1 f1 = Appliction.OpenForms.OfType<Form1>().FirstOrDefault();
if (f1 != null)
{
    f1.getinfolabel(sender as Label);
}

【讨论】:

    猜你喜欢
    • 2020-08-08
    • 1970-01-01
    • 2012-04-20
    • 2020-08-12
    • 2020-07-10
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多