考虑:
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//int[] val = { 0, 0};
int val;
if (textBox1.Text == "")
{
MessageBox.Show("Input any no");
}
else
{
val = Convert.ToInt32(textBox1.Text);
Thread ot1 = new Thread(new ParameterizedThreadStart(SumData));
ot1.Start(val);
}
}
private static void ReadData(object state)
{
System.Windows.Forms.Application.Run();
}
void setTextboxText(int result)
{
if (this.InvokeRequired)
{
this.Invoke(new IntDelegate(SetTextboxTextSafe), new object[] { result });
}
else
{
SetTextboxTextSafe(result);
}
}
void SetTextboxTextSafe(int result)
{
label1.Text = result.ToString();
}
private static void SumData(object state)
{
int result;
//int[] icount = (int[])state;
int icount = (int)state;
for (int i = icount; i > 0; i--)
{
result += i;
System.Threading.Thread.Sleep(1000);
}
setTextboxText(result);
}
delegate void IntDelegate(int result);
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
为什么会出现这个错误?
非静态字段、方法或属性“WindowsApplication1.Form1.SetTextBoxText(int)”需要对象引用
看起来您正在从静态方法(特别是sumdata
)调用非静态成员(属性或方法,特别是settextboxtext
)。您需要执行以下操作:
>
还将被调用成员设置为静态:
static void setTextboxText(int result)
{
// Write static logic for setTextboxText.
// This may require a static singleton instance of Form1.
}
在调用方法内创建form1
的实例:
private static void SumData(object state)
{
int result = 0;
//int[] icount = (int[])state;
int icount = (int)state;
for (int i = icount; i > 0; i--)
{
result += i;
System.Threading.Thread.Sleep(1000);
}
Form1 frm1 = new Form1();
frm1.setTextboxText(result);
}
传入form1
的实例也是一种选择。
使调用方法成为非静态实例方法(form1
):
private void SumData(object state)
{
int result = 0;
//int[] icount = (int[])state;
int icount = (int)state;
for (int i = icount; i > 0; i--)
{
result += i;
System.Threading.Thread.Sleep(1000);
}
setTextboxText(result);
}
有关此错误的详细信息可在MSDN上找到。
在这种情况下,您想要获得一个窗体的控制,但却收到了这个错误,那么我有一个小的旁路给您。
转到您的程序.cs并更改
Application.Run(new Form1());
至
public static Form1 form1 = new Form1(); // Place this var out of the constructor
Application.Run(form1);
现在可以使用
Program.form1.<Your control>
另外:不要忘记将控制访问级别设置为public。
是的,我知道,这个答案不适合提问者,但它适合谷歌人谁有这个具体的控制问题。