0

別のメソッドを呼び出すとプロパティが更新されませんTextBoxか?Label TextForm

ここにコードがあります

//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 の既存のインスタンスのラベルを更新することです。そのため、Button1_Click イベント ハンドラーで作成した Form1 に Form2 のインスタンスを渡す必要があります。または (より良い方法) 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 に答える