考虑:

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();
        }
    }
}

为什么会出现这个错误?

对于非静态字段、方法或属性,需要一个对象引用


当前回答

从我的寻找你给一个空值的文本框,并返回一个ToString(),因为它是一个静态方法。你可以用Convert.ToString()替换它,它可以启用空值。

其他回答

您的方法必须是静态的

static void setTextboxText(int result)
{
    if (this.InvokeRequired)
    {
        this.Invoke(new IntDelegate(SetTextboxTextSafe), new object[] { result }); 
    }
    else
    {
        SetTextboxTextSafe(result);
    }
}

这要归功于@COOLGAMETUBE,是他向我透露了最终适合我的方法。他的想法很好,但我在申请时遇到了一个问题。SetCompatibleTextRenderingDefault在表单创建后被调用。所以稍微改变一下,这对我来说是可行的:

静态类程序 { public static Form1;// = new Form1();//把这个变量放在构造函数外面

/// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(form1 = new Form1()); } }

使函数是静态的。这一定能解决你的问题。

对于这种情况,当您想要获得窗体的控件并接收此错误时,我为您提供了一个小绕过。

进入Program.cs并进行更改

Application.Run(new Form1());

to

public static Form1 form1 = new Form1(); // Place this var out of the constructor
Application.Run(form1);

现在可以访问控件

Program.form1.<Your control>

另外:不要忘记将你的Control-Access-Level设置为Public。

是的,我知道,这个答案不适合问题调用者,但它适合谷歌人谁有这个特定的问题与控制。

我实际上得到了这个错误,因为我正在检查InnerHtml的一些内容是动态生成的-即一个控件是runat=server。

为了解决这个问题,我不得不在我的方法上删除“static”关键字,它运行得很好。