Click here to Skip to main content
15,616,746 members
Please Sign up or sign in to vote.
4.33/5 (3 votes)
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 DataGridView just wide enough to avoid a 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 DataGridView to in order to remove the scroll bar from it.
Updated 11-Jul-11 9:19am
wizardzz 11-Jul-11 10:27am    
Good question, I've never had to do this but I'm curious how.
wizardzz 11-Jul-11 16:25pm    
Are the dynamically added columns of a fixed width? Could you force them to be?
Dan Neely 11-Jul-11 17:01pm    
They are fixed width.
wizardzz 11-Jul-11 17:07pm    
Is it possibly to just calculate numbers of columns by the fixed widths + a fixed buffer? Obviously I'm not sure if this would work so I'm putting it as a comment, not solution. I think I may have hacked something like that together in the past.

Seems like, you can have your chart and DataGridView fixed sized, and just use the AutoSizeColumnMode to fit the columns in view without scrollbar.[^]
Share this answer
Dan Neely 12-Jul-11 8:42am    
That's not a suitable option. At the high end a scroll bar is needed to give enough space to allow the columns to be big enough to show the numbers. At the low end having 6 2" wide columns that are 90% empty and of which only 3 are visible isn't acceptable either.
Wizardzz was on the right track; I got this from another site:

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

    // Return the width of all columns plus the row header, and adjusted for the DataGridView's BorderStyle.
    return dataGridView.Columns.GetColumnsWidth(DataGridViewElementStates.Visible) + dataGridView.RowHeadersWidth + controlBorderWidth;
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900