Reputation: 318
I'm trying to make a window forms application in which I need to hide and show rows of a datagridView quite frequently. Currently and using a loop
for (int i=0;i<grid.Rows.Count;i++){
grid.Rows[i].Visible = false;
}
But this is making my UI too slow, is there a faster way to do this?? Thanks in advance.
Upvotes: 4
Views: 14802
Reputation: 148
VB.net rather than C#:
Turning on DoubleBuffering will improve your performance:
dgvMain.[GetType].GetProperty("DoubleBuffered", BindingFlags.Instance Or BindingFlags.NonPublic).SetValue(dgvMain, True, Nothing)
Also dgvMain.SuspendLayout()
and dgvMain.ResumeLayout()
may help.
I found an additional boost in performance by hiding all the DataGridView Columns (and the DataGridViewRow Headers) before running the row hiding function and then making the columns / headers visible again after.
-OO-
Upvotes: 0
Reputation: 54433
You can remove all rows after storing them in a list and add them back as needed:
List<DataGridViewRow> rows = null;
// prepare list
rows = new List<DataGridViewRow>();
// copy rows to list
rows.AddRange(dataGridView1.Rows.Cast<DataGridViewRow>());
// remove them all
dataGridView1.Rows.Clear();
// add them back:
dataGridView1.Rows.AddRange(rows.ToArray());
// clean up
rows.Clear();
Upvotes: 4
Reputation: 746
What you could do is if you are using the DataSource as input:
For normal operation:
grid.DataSource = yourList;
In case you want to hide certain elements:
grid.DataSource = yourList.Where(x => x.SomeBool).ToArray();
Note:
Sometimes the datasource isn't fully renewed like this, therefore you could try to set it to null first, resulting in:
grid.DataSource = null;
grid.DataSource = yourList.Where(x => x.SomeBool).ToArray();
Upvotes: 4