Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically resize DataGridView to remove scroll bars

I have a DataGridView with a user definable number of columns (anywhere from ~6-60) of numerical data. At the higher end that amount of data in the grid exceeds that which can be displayed on screen at once. I have a graph that goes with the data. I would like to keep the two in sync, so that a specific time T on the graph is in line vertically with the same time in the grid.

To do this I'd like to make the DGV just wide enough to avoid a horizontal scroll bar, have the graph be equally wide, and then offload the scrolling onto a container control. However, I can't find a way to directly get the width I'd need to set the DGV to in order to remove the scroll bar from it.

like image 518
Dan Is Fiddling By Firelight Avatar asked Jul 11 '11 14:07

Dan Is Fiddling By Firelight


2 Answers

This will resize the columns to fit the space they are provided with and it will remove the horizontal scrollbar.

dgv.AutoSizeColumnsMode  = DataGridViewAutoSizeColumnsMode.Fill;

This will resize the columns to become the smallest possible width and still keep the values on the cells visible and it will automatically resize the datagridview to fit the columns, but the horizontal scrollbar may appear if the form is not big enough. In that case, you would have to resize the form's width.

dgv.AutoSizeColumnsMode  = DataGridViewAutoSizeColumnsMode.AllCells;
like image 45
A. Abiri Avatar answered Nov 12 '22 22:11

A. Abiri


To prevent a DataGridView from displaying its horizontal scrollbar you'll need to make sure your DGV's width is not less than the width of its columns plus the row header's width. You'll also need to adjust for the two pixels that are added to the control's width (and height) when its BorderStyle property is not None.

Here's a method which will return this minimum value for a given 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;
}
like image 69
Jay Riggs Avatar answered Nov 12 '22 22:11

Jay Riggs