自动调整 DataViewGrid 大小,使其永不出现水平滚动条






3.91/5 (7投票s)
2005年4月10日
1分钟阅读

86304
当您调整窗体大小时,您不希望 DBGrid 上出现水平滚动条。这段代码片段以一种智能的方式调整网格中的所有列。
引言
本文档描述了如何在窗体调整大小后调整 DBGrid 的大小,使其适应窗体,从而没有水平滚动条。要使用它,您需要在包含 DBGrid 的窗体中添加以下代码
int PrevWidth;
public Form1()
{
InitializeComponent();
PrevWidth = dataGrid.Width;
}
private void Form1_ResizeEnd(object sender, EventArgs e)
{
dataGrid_Resize(dataGrid, ref PrevWidth);
}
您也可以从 Resize
事件中调用它。优点是它在用户调整大小时进行良好的调整,但缺点是它会多次计算大量的 CPU 和列,并且如果窗体缓慢调整大小,则会出错。因此,最好处理 ResizeEnd
事件。这是执行繁重工作代码。我把它放在一个 static
class
中,以便所有窗体都可以使用相同的代码来调整大小(这就是为什么 PrevWidth
保存在窗体本身中)。
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;
}
它首先重新计算所有列的宽度(如果有可见列)。最后,我们可能会出现四舍五入误差,并且如果最后一列的宽度为 1 个像素或更多,则仍然会出现滚动条。因此,我们最终计算出最后一列所需的精确宽度。
请注意,我只是 C# 的初学者,所以任何评论(包括负面评论)或改进都将受到欢迎:)