0

I am using one thread running this code:

try
{
    Form1 f = getForm<Form1>();
    f.changePrice(price);
}
catch (Exception e)
{
    Console.WriteLine("error: " + e);
}

Here is the changePrice method:

public void changePrice(Int32 price)
{
   txtPrice.Text = ""+price;
}

I want to add text to my textbox "txtPrice".

Bridge
  • 29,818
  • 9
  • 60
  • 82
EnginBekar
  • 43
  • 6

2 Answers2

1

convert it to string as Text property is of type string:

public void changePrice(Int32 price)
{
   txtPrice.Text = price.ToString();

}
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • That's not necessary, all C# built-in types can be implicitly converted to string, there's no need to do it manually. – Kamil T May 14 '14 at 11:21
  • i did'nt got what you are trying to say, Op is setting Text of TExtBox and it requires ``String`` not ``Int`` – Ehsan Sajjad May 14 '14 at 11:23
  • `TextBox.Text` is a `string` object and you can use (for example) `string _Text = "partOfString"+5;`. The compiler will merge the `"partOfString"+5` into a string itself, because `Int32` is implicitly converted to string. It will work as long as there is a piece of string in the expression. OP's approach, the `txtPrice.Text = ""+price;` is surely not neat, but still it's not the main issue. – Kamil T May 14 '14 at 11:26
  • ok.. thanks for correcting me, i was not aware of this behaviour – Ehsan Sajjad May 14 '14 at 11:27
  • I am still getting a invalidoperationexception. It says "action across threads is invalid" – EnginBekar May 14 '14 at 11:30
  • what is the definition of ``getForm()`` ?? – Ehsan Sajjad May 14 '14 at 11:38
1

You should change your textbox text at runtime like this.

public void changePrice(Int32 price)
    {
        if (InvokeRequired)
        {
            this.Invoke(new Action<Int32>(changePrice), new object[] { price });
            return;
        }

        txtPrice.Text = ""+ price;          
    }

This will do the trick.

Friis1978
  • 1,179
  • 9
  • 16
  • you should see the answers in this question, pretty much explains it..http://stackoverflow.com/questions/6614157/help-with-understanding-c-sharp-syntax-while-invoking-a-new-action – Friis1978 May 14 '14 at 18:58