Introduction
The article describes how you can resize A DBGrid to fit the form
After a resize, so that there is no horizontal scrollbar. To use it,
You need the following code in the form where your DBGrid is sitting:
<SPAN class = "CS-keyword"> int </span> prevwidth; <br> <SPAN class = "CS-keyword"> Public </span> form1 () <br >{< br> initializecomponent (); <br> prevwidth = DataGrid. width; <br >}< br> <SPAN class = "CS-keyword"> private </span> <SPAN class = "CS-keyword"> void </span> form1_resizeend (<SPAN class = "CS-keyword"> Object </span> sender, eventargs e) <br >{< br> datagrid_resize (DataGrid, <SPAN class = "CS-keyword"> ref </span> prevwidth); <br>} |
You can also call it fromResize
Event.
Advantage is that it does a nice resizing when the user resizes,
The disadvantage of it is that a lot of silly CPU and columns are
Calculated into a times, and that it will be messed up if the form is
Slowly sized. So it is better to deal withResizeend
Event. This is the code that does the horse work. I put it inStatic
Class
So that all the forms can use the same code to do the resizing (that's whyPrevwidth
Is held in the form itself ).
Collapse
Public Void Datagrid_resize ( Object Sender,Ref Int Prevwidth)
{
Datagridview DataGrid = (datagridview) sender;
If (Prevwidth = 0 )
Prevwidth = DataGrid. width;
If (Prevwidth = DataGrid. width)
Return ;
// Const int scrollbarwidth = 18;
// Int fixedwidth = scrollbarwidth + DataGrid. rowheaderswidth;
Int Fixedwidth = systeminformation. verticalscrollbarwidth +
DataGrid. rowheaderswidth + 2 ;
Int Mul =
100 * (DataGrid. Width-fixedwidth)/(prevwidth-fixedwidth );
Int W;
Int Total = 0 ;
Int Lastcol = 0 ;
For ( Int I = 0 ; I <DataGrid. columncount; I ++)
If (DataGrid. Columns [I]. Visible ){
W = (DataGrid. Columns [I]. Width * Mul + 50 )/ 100 ;
DataGrid. Columns [I]. width =
Math. Max (W, DataGrid. Columns [I]. minimumwidth );
Total + = DataGrid. Columns [I]. width;
Lastcol = I;
}
Total-= DataGrid. Columns [lastcol]. width;
W = DataGrid. Width-total-fixedwidth;
DataGrid. Columns [lastcol]. width =
Math. Max (W, DataGrid. Columns [lastcol]. minimumwidth );
Prevwidth = DataGrid. width;
}
What it does first is it recalculates all the columns width (if
There are visible columns). In the end, we can have Rounding Errors and
Still have a scrollbar if the last column is 1 or more pixels wide. So
We calculate the exact width needed for the last column in the end.
Please note that I'm only a beginner in C #, so any comments (also negative) or improvements are welcome