从其他表单调用方法时,为什么控件不更新 [英] Why the controls not update, when call method from other form

查看:18
本文介绍了从其他表单调用方法时,为什么控件不更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My TextBox and Label Text property does not update when I call a method from another 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();
}

提前致谢.

推荐答案

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

You are creating new instance of Form2 (which in not visible to client, because you don't show it) and updating it's label. What you need is updating label on existing instance of Form2. So, you need to pass instance of Form2 to Form1, which you create in Button1_Click event handler. Or (the better way) you need to define property on Form1 and read that property when Form1 is closed:

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();
}

这篇关于从其他表单调用方法时,为什么控件不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆