0

当我从另一个调用方法时,我的TextBoxLabel Text属性不会更新Form

这是代码

//Form1 Codes
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
    Form2 frm= new Form2 ();
    frm.UpdateText(this.treeView1.SelectedNode.Text.ToString());
    this.Close();
}

//Form2 codes
//show Form1
private void Button1_Click(object sender, EventArgs e)
{
    Form1 Frm = new Form1();
    Frm.ShowDialog();
}

//update Textbox and lable
public void UpdateText(string text)
{
    this.label1.Text = text;
    textBox1.Text = text;
    label1.Refresh();
}

提前致谢。

4

1 回答 1

2

您正在创建Form2 的新实例(对客户端不可见,因为您没有显示它)并更新它的标签。您需要更新 Form2 现有实例上的标签。因此,您需要将 Form2 的实例传递给您在 Button1_Click 事件处理程序中创建的 Form1。或者(更好的方法)您需要在 Form1 上定义属性并在 Form1 关闭时读取该属性:

Form1 代码

public string SelectedValue 
{ 
     get { return treeView1.SelectedNode.Text; }
}    

void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
     // this means that user clicked on tree view
     DialogResult = DialogResult.OK;
     Close();
}

Form2 代码

private void Button1_Click(object sender, EventArgs e)
{
    using(Form1 frm1 = new Form1())
    {
       if(frm1.ShowDialog() != DialogResult.OK)
          return;

       UpdateText(frm1.SelectedValue);
    }
}

public void UpdateText(string text)
{
    label1.Text = text;
    textBox1.Text = text;
    label1.Refresh();
}
于 2012-12-17T08:16:25.660 回答