在Form2中单击按钮后,使Form1中的LabelText可见

时间:2017-03-09 07:35:53

标签: c# winforms

我在private void button1_Click(object sender, EventArgs e) { if (listBox1.SelectedIndex > 0) { int selectedIndex = listBox1.SelectedIndex; object selectedItem = listBox1.SelectedItem; listBox1.Items.Remove(selectedItem); listBox1.Items.Insert(selectedIndex - 1, selectedItem); listBox1.SetSelected(selectedIndex -1, true); // here we go } } 中设置了LabelText隐身,Form1中有button。如果我在Form2中隐藏了buttonForm2中的LabelText将会显示。但是,我正试图解决它,但仍然无法正常工作。

在Form1中:

Form1

在Form2中:

public void LabelText()
{
   label1.Visible = true;
}

1 个答案:

答案 0 :(得分:2)

您正在创建Form1的新实例,而不是使用之前显示的现有实例。

你也可以  1.使用静态类来保留所有句柄 要么  2.在Form2 ctor中传递Form1实例

1

internal static class FormManager
{
    public static Form1 Form1Handle;
    public static Form2 Form2Handle;
}

然后在构造函数

public Form1()
{
   FormManager.Form1Handle = this;
}

并相应地为Form2或

2。 覆盖Form2 ctor

private Form1 _form1;

public Form2(Form1 form1Handle)
{
   _form1 = form1Handle;
}

然后从Form1调用Form2,如下所示:

Form2 f2 = new Form2(this);
f2.ShowDialog();

然后根据情况使用它:

  1. FormManager.LabelText();
  2. _form1.LabelText();