I have a DataGridView that I add a DataGridViewComboBoxColumn to, add values, and set the Value by iterating through the grid rows. 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. I have tried iterating via row count and using a foreach loop (in commented code below) with same results. 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. 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);
}