DataGrid Column adjustments during resizing form (using ParamArray)






1.05/5 (8 votes)
Apr 9, 2004

56576

739
Automatically handle to adjust grid widths
Introduction
AutoSize of columns based on the user resizing of the form is a not good way to do it. But, through this article, it is going to explain how can resize a grid columns using a single function.
"GridResizeColumns" Procedure
The "GridResizeColumns" function will adjust the columns while you resizing the VB form. This procedure will support both VB6 and VB.NET applications.
Parameters
There are four parameters are listed:
1. DataGridView - Control - This will be Your Grid Control Name
2. FixedTotalWidth - Double - This will be your total Fixed Grid Width (Say for eg. eg., you may want to keep a check box in a grid that needs to be fixed size. )
3. StartCol - Integer - This identifies which column do you want to start to resize
4. ColumnWidthInPercent() - ParamArray & Double - You can assign each column percentage size.
Sample Code
The following the sample code of the "GridResizeColumns" procedure. You can also download full source code for this.
Private Sub GridResizeColumns(ByVal DataGridView As Control,_
ByVal FixedTotalWidth As Double, _
ByVal StartCol As Integer,_
ByVal ParamArray ColumnWidthInPercent() As Double)
Dim TotalGridWidth As Long
Dim intIndex As Integer
Dim PercentColWidth As Integer
On Error GoTo ErrHandler
With DataGridView1
'Exclusing Fixed column width
TotalGridWidth = DataGridView.Width - FixedTotalWidth
.ScrollBars = flexScrollBarVertical
For Each PercentColWidth In ColumnWidthInPercent
.Columns(StartCol).Width = (PercentColWidth / 100) * TotalGridWidth
StartCol = StartCol + 1
Next
.Refresh()
End With
Exit Sub
ErrHandler:
Exit Sub
End Sub
Example:
GridResizeColumns(MyDataGridView1, 0, 0, 25, 25, 25, 25)