Autoresize a DataViewGrid to never have horizontal scrollbar

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:

   int PrevWidth;
public Form1()
{
InitializeComponent();
PrevWidth = dataGrid.Width;
}

private void Form1_ResizeEnd(object sender, EventArgs e)
{
dataGrid_Resize(dataGrid, ref PrevWidth);
}

You can also call it from the Resize event. The advantage is that it does a nice resizing when the user resizes, but the disadvantage of it is that a lot of silly CPU and columns are calculated many a times, and that it will be messed up if the form is slowly sized. So it is better to deal with the ResizeEnd event. This is the code that does the horse work. I put it in a static class so that all the forms can use the same code to do the resizing (that's why the PrevWidth 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 :)

你可能感兴趣的:(scroll)