当我从另一个TextBox
调用某个方法时,我的Label
和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();
}
提前致谢。
答案 0 :(得分: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();
}