In this post, we will show you how to hide a column from the DataGridView when the user groups the data by the column. When the user ungroups by the column, we will show the column again.
The first step is to subscribe to the CollectionChanged event of the vDataGridView's GroupingColumns collection.
C#
this.Grid1.GroupingColumns.CollectionChanged += new EventHandler<CollectionChangedEventArgs>(GroupingColumns_CollectionChanged);
VB .NET
AddHandler Grid1.GroupingColumns.CollectionChanged, AddressOf GroupingColumns_CollectionChanged
2. The next step is to update the DataGridView Columns Visibility in the event handler.
C#
void GroupingColumns_CollectionChanged(object sender, CollectionChangedEventArgs e)
{
HierarchyItemsCollection items = Grid1.ColumnsHierarchy.Items;
foreach (BoundField field in Grid1.GroupingColumns)
{
foreach (HierarchyItem item in items)
{
if (item.Caption == field.Text)
{
item.Hidden = true;
items.Remove(item);
break;
}
}
}
}
VB .NET
Private Sub GroupingColumns_CollectionChanged(ByVal sender As Object, ByVal e As CollectionChangedEventArgs)
Dim items As HierarchyItemsCollection = Grid1.ColumnsHierarchy.Items
For Each field As BoundField In Grid1.GroupingColumns
For Each item As HierarchyItem In items
If item.Caption = field.Text Then
item.Hidden = True
items.Remove(item)
Exit For
End If
Next item
Next field
End Sub