Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# System.InvalidOperationException设置文本框文本_C#_Multithreading_Forms_User Interface_Invalidoperationexception - Fatal编程技术网

C# System.InvalidOperationException设置文本框文本

C# System.InvalidOperationException设置文本框文本,c#,multithreading,forms,user-interface,invalidoperationexception,C#,Multithreading,Forms,User Interface,Invalidoperationexception,我正在使用一个线程运行以下代码: try { Form1 f = getForm<Form1>(); f.changePrice(price); } catch (Exception e) { Console.WriteLine("error: " + e); } 我想将文本添加到我的文本框“txtPrice”中。将其转换为string,因为text属性的类型为string: public void changePrice(Int32 price) {

我正在使用一个线程运行以下代码:

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

我想将文本添加到我的文本框“txtPrice”中。

将其转换为
string
,因为
text
属性的类型为
string

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

}

您应该像这样在运行时更改文本框文本

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

        txtPrice.Text = ""+ price;          
    }
public void changePrice(Int32价格)
{
如果(需要调用)
{
调用(新操作(changePrice),新对象[]{price});
返回;
}
txtPrice.Text=”“+价格;
}

这样就可以了。

将空字符串添加到整数中?请开始阅读。
changePrice
是否由
拥有
Form1
的同一线程使用?您不能以这种方式从其他线程更改
控件的属性。它是从其他线程使用的,有什么建议吗?您不能这样做,请使用下面描述的方法:错误消息到底说了什么?这不是必需的,所有C#内置类型都可以隐式转换为字符串,不需要手动操作。我不明白你想说的,Op是设置文本框的文本,它需要
String
not
Int
TExtBox。Text
String
对象,你可以使用(例如)
String\u Text=“partOfString”+5。编译器将把
“partOfString”+5
合并为字符串本身,因为
Int32
被隐式转换为字符串。只要表达式中有一段字符串,它就可以工作。OP的方法,
txtPrice.Text=”“+价格
当然不整洁,但它仍然不是主要问题。好吧。。谢谢你纠正我,我没有意识到这种行为,我仍然得到一个残疾手术例外。它说“跨线程的操作是无效的”,你应该看到这个问题的答案,这很好地解释了它。。
public void changePrice(Int32 price)
    {
        if (InvokeRequired)
        {
            this.Invoke(new Action<Int32>(changePrice), new object[] { price });
            return;
        }

        txtPrice.Text = ""+ price;          
    }