当我从另一个表单调用方法时,控件不会更改颜色或文本

Controls do not change color or text, when I call method from another form

注意:Form2是MDI子窗体,我把Form1的修饰符全部设置为Public

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

在表格 2 中:

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