Category / Section
How to auto extend a column to fill the available space in the WinForms GridGroupingControl?
1 min read
Handle QueryColWidth event
To dynamically change the column widths, you have to handle the Grid's QueryColWidth event. The following example shows how you can have the right-most or the left-most column grow to fill the Grid's client area as the Grid size changes.
C#
//Defines the columns to fill the space in the table. void TableModel_QueryColWidth(object sender, GridRowColSizeEventArgs e) { switch (_colSizeBehavior) { case colSizeBehavior.RightColumn: if(e.Index == this.gridGroupingControl1.TableDescriptor.VisibleColumns.Count) { e.Size = this.gridGroupingControl1.ClientSize.Width - this.gridGroupingControl1.TableModel.ColWidths.GetTotal(0, this.gridGroupingControl1.TableDescriptor.VisibleColumns.Count - 1); e.Handled = true; } break; case colSizeBehavior.LeftColumn: if(e.Index == this.gridGroupingControl1.TableModel.Cols.FrozenCount + 1) { int leftPiece = this.gridGroupingControl1.TableModel.ColWidths.GetTotal(0, this.gridGroupingControl1.TableModel.Cols.FrozenCount); int rightPiece = this.gridGroupingControl1.TableModel.ColWidths.GetTotal(this.gridGroupingControl1.TableModel.Cols.FrozenCount + 2, this.gridGroupingControl1.TableModel.ColCount); e.Size = this.gridGroupingControl1.ClientSize.Width - leftPiece - rightPiece; e.Handled = true; } break; default: break; } }
VB
'Defines the columns to fill the space in the table. Private Sub TableModel_QueryColWidth(ByVal sender As Object, ByVal e As GridRowColSizeEventArgs) Select Case _colSizeBehavior Case colSizeBehavior.RightColumn If e.Index = Me.gridGroupingControl1.TableDescriptor.VisibleColumns.Count Then e.Size = Me.gridGroupingControl1.ClientSize.Width - Me.gridGroupingControl1.TableModel.ColWidths.GetTotal(0, Me.gridGroupingControl1.TableDescriptor.VisibleColumns.Count - 1) e.Handled = True End If Case colSizeBehavior.LeftColumn If e.Index = Me.gridGroupingControl1.TableModel.Cols.FrozenCount + 1 Then Dim leftPiece As Integer = Me.gridGroupingControl1.TableModel.ColWidths.GetTotal(0, Me.gridGroupingControl1.TableModel.Cols.FrozenCount) Dim rightPiece As Integer = Me.gridGroupingControl1.TableModel.ColWidths.GetTotal(Me.gridGroupingControl1.TableModel.Cols.FrozenCount + 2, Me.gridGroupingControl1.TableModel.ColCount) e.Size = Me.gridGroupingControl1.ClientSize.Width - leftPiece - rightPiece e.Handled = True End If Case Else End Select End Sub
After applying the properties, the Grid looks like the following screenshot.
Figure 1: The left column to fill the available space
Samples: