An object reference is required for the non-static field, method, or property message

D

Dave

The problem is with my listbox on the form.
I am trying to run 2 threads simulataneously an update two different listbox
controls but my functions are complaining that the listbox doesn't have an
object reference, my listboxes were created by the ide and drawn on the
form at design time.
How can I give my listbox a reference?
Thanks

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{

static List<string> list = new List<string>();
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
new Thread(AddItems1).Start();
new Thread(AddItems2).Start();
}
static void AddItems1()
{
for (int i = 0; i < 10000; i++)
//lock (list)
list.Add("Item " + list.Count);

string[] items;
items = list.ToArray();
foreach (string s in items) Form1.listBox1.Items.Add(s);
}
static void AddItems2()
{
for (int i = 0; i < 10000; i++)
//lock (list)
list.Add("Item " + list.Count);

string[] items;
items = list.ToArray();
foreach (string s in items) Form1.listBox2.Items.Add(s);
}

}

}
 
P

Pavel Minaev

The problem is with my listbox on the form.
I am trying to run 2 threads simulataneously an update two different listbox
controls but my functions are complaining that the listbox doesn't have an
object reference,  my listboxes were created by the ide and drawn on the
form at design time.
How can I give my listbox a reference?

Very simple: make methods you use as thread entry points (in your
case, AddItems1 and AddItems2) non-static.

In addition to that, you cannot call (most) methods and properties on
Windows Forms controls from any thread other than the one which had
created them. In your case, trying to add an item to the ListBox from
another thread will result in an exception. You can work around this
by using Control.Invoke and Control.BeginInvoke as needed - MSDN has
more details and examples, as usual.
 
F

Family Tree Mike

I believe the line below, and a similar one later:

foreach (string s in items) Form1.listBox1.Items.Add(s);

should be:

foreach (string s in items) this.listBox1.Items.Add(s);

Hope this help...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top