简体   繁体   中英

C# adding rows to a datagridview

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM