My dataGridView contains multiple columns. I can hide individual columns, but then I want the ability to show all columns again. I can do this with a for statement; however, I thought I should be able to do it with a foreach as well; however, I cannot get the syntax right.
My working for statement:
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
dataGridView1.Columns[i].Visible = true;
}
What I tried in the foreach statement:
foreach (var column in dataGridView1.Columns)
{
dataGridView1.Columns[column].Visible = true;
}
I understand that I need the index value for the column; however, I'm missing how to get it from the column value. What's really driving me crazy is that I know its something simple that I'm missing!
On a side note, is it better to use a for or foreach for this? Or is there really any benefit of one over the other?
Thank you for your help. Brian.
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
column.Visible = true;
}
With the foreach
, you can act directly on the object. In this case, the only benefit is readability really, although it also removes the need for an extra int
variable. In general, foreach
can be more efficient, because it leaves the implementation up to the individual collection class, which of course knows the most efficient way to enumerate itself. Example: HashSet
Note that because the Columns
property is a DataGridViewColumnCollection
, which implements IEnumerable
rather than IEnumerable<DataGridViewColumn>
or similar, you must specify the type of your variable. If you say var
, you will get object
.
I believe this is because DataGridView
was designed before generics were implemented.