无法从其他表单更改TextBox.Text

时间:2016-05-13 09:39:57

标签: c# winforms textbox

我在winform应用程序中有以下C#代码:

FormPrincipale

private void butFornitore_Click(object sender, EventArgs e)
{
  try
  {
    FormFornitore Dialog = new FormFornitore();
    Dialog.ShowDialog();
  }
  catch(Exception excDial)
  {
    MessageBox.Show("DIALOG: " + excDial.Message);
  }
}

public void getFornitore(string Codice, string Descrizione)
{
  this.txtFornitore.Text = Descrizione;
  Fornitore = Codice;
}

FormFornitore

private void gridFornitori_DoubleClick(object sender, EventArgs e)
{
  try
  {
    var Codice = gridView2.GetFocusedDataRow()["codconto"].ToString();
    var RagSoc = gridView2.GetFocusedDataRow()["dscconto1"].ToString();
    FormPrincipale Form = new FormPrincipale();
    Form.getFornitore(Codice, RagSoc);
    this.Close();
  }
  catch(Exception excGrid)
  {
    MessageBox.Show("GRID: " + excGrid.Message);
  }
}

代码有效(我使用断点来检查代码是否已执行),但TextBox的Text属性不会改变。我把Modifiers TextBox属性放在Public上,所以这也没问题。我正在使用Dev Express Grid Control,但我不认为这是问题所在。谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

要传递父表单的实例,您可以执行以下操作:

class FormFornitore: Form
{
   protected FormPrincipale parent;
   FormFornitore(FormPrincipale parent)
   {
      this.parent = parent;
   }

    private void gridFornitori_DoubleClick(object sender, EventArgs e)
    {
      try
      {
        var Codice = gridView2.GetFocusedDataRow()["codconto"].ToString();
        var RagSoc = gridView2.GetFocusedDataRow()["dscconto1"].ToString();
        /// REMOVE THIS FormPrincipale Form = new FormPrincipale();
        parent.getFornitore(Codice, RagSoc);
        this.Close();
      }
      catch(Exception excGrid)
      {
        MessageBox.Show("GRID: " + excGrid.Message);
      }
    }
}

然后在你的“FormPricipale”中使用它

private void butFornitore_Click(object sender, EventArgs e)  
{
  try
  {
    FormFornitore Dialog = new FormFornitore(this); // Notice the argument
    Dialog.ShowDialog();
  }
  catch(Exception excDial)
  {
    MessageBox.Show("DIALOG: " + excDial.Message);
  }
}

public void getFornitore(string Codice, string Descrizione)
{
  this.txtFornitore.Text = Descrizione;
  Fornitore = Codice;
}