如何从C#中的另一种形式更新一种形式的标签吗?形式、标签

2023-09-04 00:51:08 作者:囿點菈風啲侽亽

我想从窗体2 更新 Form1中的标签。所以,这里是我的:

I want to update label of Form1 from Form2. So here's what I have:

// Form1
public string Label1
{
    get { return this.label1.Text; }
    set { this.label1.Text = value; }
}


// Form2
private void button1_Click(object sender, EventArgs e)
{
    Form1 frm1 = new Form1();
    frm1.Label1 = this.textBox1.Text;
    this.Close();
}

所以上面的code不起作用。然而,当我添加以下内容:

So the above code doesn't work. However, when I add the following:

frm1.Show();

this.Close();

在窗体2 code,在Form1显然被再次打开(两个窗口)。但我想它在同一个窗口更新所以我建议 this.Close()是不必要的。

in Form2 code, the Form1 obviously is being opened again (two windows). But I want it to update in the same window so I suggest this.Close() is unnecessary.

任何人有什么想法?

推荐答案

的button1_Click 方法,你实际上是创建一个新的实例 Form1中和制定新的实例的标签1 属性。这就解释了为什么一个的第二的 Form1中的实例,当您添加被显示在屏幕上 frm1.Show(); 。如果你看一下这第二个副本细心,你会发现它的标签显示正确的值,但这种形式的原始副本保留了其原有的价值。

In the button1_Click method, you're actually creating a new instance of Form1 and setting the Label1 property of that new instance. That explains why a second instance of Form1 is being shown on the screen when you add frm1.Show();. If you look at that second copy carefully, you'll see that it's label displays the correct value, but your original copy of that form retains its original value.

相反,我认为,你想要做的是设置标签1 属性的现有的实例 Form1中什么显示在屏幕上已显示。为了做到这一点,你将必须得到一个对现有的表单对象。

Instead, I assume that what you want to do is set the Label1 property for the existing instance of Form1 that is already displayed on the screen. In order to do that, you're going to have to get a reference to that existing form object.

因此​​,这成为我怎么过两个对象(表)之间的数据,这已经被问了无数次在这里对堆栈溢出的一个简单的问题。查看回答这些相关的问题:

Thus, this becomes a simple question of "how do I pass data between two objects (forms)", which has been asked countless times here on Stack Overflow. See the answers to these related questions:

Communicate窗口的形式在C#两者之间 两个窗口之间传递价值观形成 C#初学者的帮助下,我如何通过一个数值从孩子回父窗体? Send从一种形式价值观为另一种形式在C#的WinForms应用 Communicate between two windows forms in C# Passing values between two windows forms C# beginner help, How do I pass a value from a child back to the parent form? Send values from one form to another form in c# winforms application
 
精彩推荐
图片推荐