-1

I wrote this code:

public partial class Form1 : Form
{
    ThreadStart ts = new ThreadStart(fun1);
    public Thread t1 = new Thread(ts);
    public void fun1()
    {
        DA da = new DA();

        string q = "select * from G5_table order by State";

        DataTable dt = da.Select(q);
        foreach (DataRow item in dt.Rows)
        {
            richtxtboxEN.Text = item["Word_en"].ToString();
            mode = 1;
            richtxtboxEN.TextChanged += new EventHandler(richtxtboxEN_TextChanged);
        }
    }
    private void Form1_Shown(object sender, EventArgs e)
    {     
        t1.Start();
    }
}

but i have a error field initializer cannot reference the non-static field, method, or property 'G5.Form1.fun1()

1
  • 9
    What is the connection between that error and the title? Commented Jul 26, 2013 at 1:15

2 Answers 2

2

You cannot access a non-static method within a field initializer like you are doing here:

ThreadStart ts = new ThreadStart(fun1);

You will need to define a constructor instead, like this:

public partial class Form1 : Form
{
    public Form1()
    {
        ts = new ThreadStart(fun1);
        t1 = new Thread(ts);
    }

    ThreadStart ts;
    public Thread t1;
Sign up to request clarification or add additional context in comments.

1 Comment

What was wrong with my answer, that was posted 5 minutes before? You are saying the exact same thing.
2

Change your Form1_Shown to this:

private void Form1_Shown(object sender, EventArgs e)
{   
    t1 = new Thread(new ThreadStart(fun1));  
    t1.Start();
}

then change t1 to this:

public Thread t1;

and remove ts from your class completely.

The error, is that you cant reference non-static things in field initializers. And that even includes other class-level fields.

And for clarification, a field initializer is this:

public Thread t1 = new Thread(ts);

Since Thread t1 is not a property, and is defined at class-level (outside of a method), it is a field, and it is being initialized right there in the declaration. It is referencing ts which is a non-static field, and you can not do this.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.