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

问题描述 投票:0回答:1

注意: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);
    }

好的,每个人都在这里工作,但在那里:

在Form1中:

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
    }

有帮助吗?请。

c# winforms mdi
1个回答
2
投票

代替

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.