以编程方式调整DataGridView的大小以删除滚动条

Dan*_*ely 9 c# datagridview winforms

我有一个DataGridView,其数据数据的用户可定义的列数(约6-60).在较高端,网格中的数据量超过可以一次显示在屏幕上的数据量.我有一个与数据一致的图表.我想保持两者同步,以便图表上的特定时间T在网格中垂直排列.

要做到这一点,我想让DGV足够宽以避免水平滚动条,让图形同样宽,然后将滚动卸载到容器控件上.但是,我找不到一种方法来直接获取我需要设置DGV的宽度,以便从中删除滚动条.

Jay*_*ggs 8

要防止DataGridView显示其水平滚动条,您需要确保DGV的宽度不小于其列的宽度加上行标题的宽度.您还需要调整添加到控件宽度(和高度)的两个像素,而BorderStyle不是它的属性None.

这是一个方法,它将返回给定DataGridView的最小值:

/// <summary>
/// Return the minimum width in pixels a DataGridView can be before the control's vertical scrollbar would be displayed.
/// </summary>
private int GetDgvMinWidth(DataGridView dgv) {
    // Add two pixels for the border for BorderStyles other than None.
    var controlBorderWidth = (dgv.BorderStyle == BorderStyle.None) ? 0 : 2;

    // Return the width of all columns plus the row header, and adjusted for the DGV's BorderStyle.
    return dgv.Columns.GetColumnsWidth(DataGridViewElementStates.Visible) + dgv.RowHeadersWidth + controlBorderWidth;
}
Run Code Online (Sandbox Code Playgroud)