Question

I am trying to display a list of 10 items within a list box and once it reaches that limit the listbox clears itself and the threading starts again. Here is the code that I have so far:

    List<string> MyList { get; set; }

    public Form1()
    {
        InitializeComponent();

        List<string> MyList = new List<string>();

        var bw = new BackgroundWorker();
        bw.DoWork += (sender, args) => MethodToDoWork();
        bw.RunWorkerCompleted += (sender, args) => MethodToUpdateControl();
        bw.RunWorkerAsync();

    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 frm2 = new Form2();
        frm2.Show();

        this.Hide();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        lbxPosition.Items.Clear();
    }

    private void MethodToDoWork()
    {
        for (int i = 0; i < 10; i++)
        {
            MyList.Add(string.Format("Temprature {0}", i));
            Thread.Sleep(100);
        }
    }

    private void MethodToUpdateControl()
    {
        lbxPosition.Items.AddRange(MyList.ToArray());
    }

Only thing is I am getting an error at line MyList.Add(string.Format("Temprature {0}", i));. My error is An exception of type 'System.NullReferenceException' occurred in s00107997.exe but was not handled in user code. Can anyone see where I am going wrong?

Was it helpful?

Solution

You have to assign your global variable inside your Form without re-writing your variable's name. In addition, do not use Thread.Sleep.

List<string> MyList { get; set; }

public Form1()
{
    InitializeComponent();

    MyList = new List<string>(); //Here was wrong.

    var bw = new BackgroundWorker();
    bw.DoWork += (sender, args) => MethodToDoWork();
    bw.RunWorkerCompleted += (sender, args) => MethodToUpdateControl();
    bw.RunWorkerAsync();

}

private void button1_Click(object sender, EventArgs e)
{
    Form2 frm2 = new Form2();
    frm2.Show();

    this.Hide();
}

private void Form1_Load(object sender, EventArgs e)
{
    lbxPosition.Items.Clear();
}

private void MethodToDoWork()
{
    for (int i = 0; i < 10; i++)
    {
        MyList.Add(string.Format("Temprature {0}", i));
    }
}

private void MethodToUpdateControl()
{
    lbxPosition.Items.AddRange(MyList.ToArray());
}

OTHER TIPS

If you want to perform such as task inside of a form, I would recommend you to use the Timer. It is better supported in WinForms as your own threads. You can get a number of problems when accessing a WinForm from another thread.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top