How to change the value of a textbox by another form? c#

Asked

Viewed 20 times

0

I have two forms: 'Sales' and 'productsDaVenda'

and a general variable that is in the code as Unique_home.Program.vendas.preco:

public static class vendas
    {
       

        public static string preco { set; get; }

    }

in the sales form I have this function:

public void getValor()
{
  TXTvalor.Text = Unique_Home.Program.vendas.preco; //TXTvalor do form 'vendas'
}

this function updates the text of the textbox to the value of the variable

In the form 'productosDaVenda' I want to call this function and I am using the following code:

private void BTNok_Click(object sender, EventArgs e)
    {
        Unique_Home.Program.vendas.preco = TXTvalor.Text; //TXTvalor do form 'produtosDaVenda'

        foreach (Vendas oForm1 in Application.OpenForms.OfType<Vendas>())
        {
            oForm1.getValor();
        }

        this.Hide();
        
    }

However, when I click on this button I am presented with this error:

System.Invalidoperationexception: 'Invalid thread operation: 'Txtvalor' control accessed from a thread that is not the one in which it was created.'

from what I understand, I cannot call the function another form. Is there any way I could allow this? Or some other way to update the value of the sales texbox via a button on the products'

NOTE: The 'sales' form is open at all times, while the 'productosDaVenda' form opens via a button in the 'sales' form. That’s the button code, just in case:

private void BTNproduto_Click(object sender, EventArgs e)
        {
            

            Unique_Home.Program.vendas.preco = TXTvalor.Text;

            trocarform = new Thread(abrirform);
            trocarform.SetApartmentState(ApartmentState.STA);
            trocarform.Start();
        }
  • Take a look at this answer and see if you can’t get a similar approach https://answall.com/questions/361898/c-windows-forms-chamando-um-form-neto-dentro-de-um-panel-form-av%C3%B4-a-partir-d/361929#361929

1 answer

0

You are trying to modify a thread control that is not the one it belongs to, try changing it as follows:

private void BTNok_Click(object sender, EventArgs e)
{
  Invoke((MethodInvoker)delegate
  {
      Unique_Home.Program.vendas.preco = TXTvalor.Text;
    
      foreach (Vendas oForm1 in Application.OpenForms.OfType<Vendas>())
      {
              oForm1.getValor();
      }
    
       this.Hide();
   });
 }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.