I have a DataGridView with a checkbox column. I'm trying to create a select/deselect all button. The code for changing the values is easy enough, but the performance is horrendous.
for (int i = 0; i < dgv.RowCount; i++)
{
dgv.Rows[i].Cells["Selected"].Value = _selectAll;
}
_selectAll is simply a toggle bool variable. Is there a better way to do this where the performance is fast? I've tried changing the value in the underlying DataTable as well. It still takes several seconds for just a few hundred rows, but most work will be done on thousands of rows.
EDIT & SOLUTION (2011/10/4)
The main problem was in the DGV properties. Once I set,
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
performance improved dramatically (per MSDN DataGridView Performance). The solutions suggested as of this edit would also improve performance slightly.
Thanks a lot, by setting the AutoSizeColumnsMode
property
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
the performance is much better...
Well, this is a common problem.
First, do you have any processing associated with the Checkbox checked change?
If so, create a bool member variable.
Initialize it to false before performing the Select All / Deselect All.
In the CheckBox checked change event -> check for the value of the bool paramter.
If it comes with false return from the event. Dont process anything.
After completing the for looping to set the select all / Deselect All, process the checked change event if necessary.
Dont forget to reset the bool parameter to true after for loop.
bool _allowProcessing = false;
//SelectAll / Deselect All
for (int i = 0; i < dgv.RowCount; i++)
{
dgv.Rows[i].Cells[4].Value = _selectAll;
}
_allowProcessing = true;
// Do some processing if required
// Checked change event
public void CheckBox_CheckedChange(object sender, eventArgs e)
{
if(!_allowProcessing)
return;
// Do Processing
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With