简体   繁体   English

System.InvalidOperationException设置texbox文本

[英]System.InvalidOperationException setting texbox text

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: 这是changePrice方法:

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

I want to add text to my textbox "txtPrice". 我想在文本框“txtPrice”中添加文本。

convert it to string as Text property is of type string : 将其转换为string因为Text属性的类型为string

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

}

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. 这样就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM