【问题标题】:C# adding rows to a datagridviewC#向datagridview添加行
【发布时间】:2011-11-23 12:10:42
【问题描述】:

我在使用字符串数组中的项目填充 datagridview 时遇到问题。这是我用来调用函数的代码:

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

还有函数本身:

        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(); }

问题是:假设数组中有 76 个项目。当我使用此代码时,它总是将第 75 项添加 76 次,仅此而已。为什么会这样?我似乎无法弄清楚我的代码有什么问题。

【问题讨论】:

    标签: c# loops datagridview row populate


    【解决方案1】:

    我想你想要:

        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(); }
    

    也就是说,将新ExplorerItem 的创建移到循环内而不是循环外。这样,在循环的每次迭代中都会创建一个新项目。如果您不在每次迭代中创建新项目,那么您就是在一遍又一遍地添加相同的项目,在每次迭代中更改其标题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-10
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多