简体   繁体   English

在DataGridViewComboBox列上设置值非常慢

[英]Setting Value on DataGridViewComboBox column very slow

I have a DataGridView that I add a DataGridViewComboBoxColumn to, add values, and set the Value by iterating through the grid rows. 我有一个DataGridView,我向其中添加了DataGridViewComboBoxColumn,添加了值,并通过遍历网格行来设置“值”。 The selected Value is the value from another row cell. 所选值是另一个行单元格中的值。 This is very slow and I'm not sure if I am using best practice or not. 这非常慢,我不确定是否正在使用最佳实践。 For a grid with 3000 rows this takes over two minutes to complete. 对于具有3000行的网格,这需要两分钟以上的时间才能完成。 I have tried iterating via row count and using a foreach loop (in commented code below) with same results. 我尝试通过行计数和使用foreach循环(在下面的注释代码中)进行迭代,结果相同。 Is there a faster way to do this? 有更快的方法吗? Here is my code: 这是我的代码:

DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
        cmb.HeaderText = "New Class";
        cmb.Name = "cmb";

        foreach (DataGridViewRow row in dgClasses.Rows)
        {
            if (row.Cells[0].Value != null)
            {
                cmb.Items.Add(row.Cells[0].Value);
            }
        }

        dgProducts.Columns.Add(cmb);

        for (int i = 0; i < dgProducts.Rows.Count; i++)
        {
            dgProducts.Rows[i].Cells["cmb"].Value = dgProducts.Rows[i].Cells["Class"].Value;
        }

        //foreach (DataGridViewRow row in dgProducts.Rows)
        //{
        //   row.Cells["cmb"].Value = row.Cells["Class"].Value;
        //}

I added DataPropertyName and got rid of the looping through the grid rows. 我添加了DataPropertyName并摆脱了遍历网格行的循环。 Loads very fast now. 现在加载非常快。

private void AddClassCombobox()
    {
        DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
        cmb.HeaderText = "New Class";
        cmb.Name = "cmb";
        cmb.DataPropertyName = "Class";  // << Added this

        foreach (DataGridViewRow row in dgClasses.Rows)
        {
            if (row.Cells[0].Value != null)
            {
                cmb.Items.Add(row.Cells[0].Value);
            }
        }

        dgProducts.Columns.Add(cmb);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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