Marco Dal Zovo
Marco Dal Zovo

Reputation: 378

Can't change TextBox.Text from another form

I have the following C# code in my winform application:

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

The code works (i used breakpoints to check if code was executed) but the Text property of the TextBox doesn't change. I put Modifiers TextBox property on Public, so this is ok too. I'm using Dev Express Grid Control, but i don't think this is the problem. Thank's for help.

Upvotes: 0

Views: 251

Answers (1)

Simo Erkinheimo
Simo Erkinheimo

Reputation: 1397

To pass the instance of your parent form, you could do something like this:

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

Then in your "FormPricipale" use it like this

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

Upvotes: 1

Related Questions