0

I am having trouble populating a datagridview with items from a string array. Here is the code I used to call the function:

ThreadPool.QueueUserWorkItem((o) => 
                ReBuildObjectExplorer();

And the function itself:

        try
        {
            List<ExplorerItem> list = new List<ExplorerItem>();
            var item = new ExplorerItem();

            for (int i = 0; i < lbl.Length; i++) // lbl = string array with items
            {
                item.title = lbl[i].Name;
                list.Add(item);
            }

            BeginInvoke((MethodInvoker)delegate
            {
                explorerList = list;
                dgvObjectExplorer.RowCount = explorerList.Count;
                dgvObjectExplorer.Invalidate();
            }); 
        }
        catch (Exception e) { MessageBox.Show(e.ToString(); }

The problem is: Suppose there are 76 items in the array. When I use this code, it ALWAYS adds the 75th item 76 times and nothing else. Why does this happen? I can't seem to figure out what is wrong with my code.

1 Answer 1

1

I think you want:

    try
    {
        List<ExplorerItem> list = new List<ExplorerItem>();

        for (int i = 0; i < lbl.Length; i++) // lbl = string array with items
        {
            var item = new ExplorerItem();
            item.title = lbl[i].Name;
            list.Add(item);
        }

        BeginInvoke((MethodInvoker)delegate
        {
            explorerList = list;
            dgvObjectExplorer.RowCount = explorerList.Count;
            dgvObjectExplorer.Invalidate();
        }); 
    }
    catch (Exception e) { MessageBox.Show(e.ToString(); }

That is, move the creation of the new ExplorerItem inside the loop rather than outside it. That way a new item is created at each iteration of the loop. If you don't create a new item in each iteration, then you are adding the same item over and over again, changing its title in every iteration.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.