Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridView Autosize but restrict max column size

in my C# 4.0 Application, I have a DataGridView to display some data. I want the Columns size accordingly to the content, so I set the AutoSizeColumnsMode to AllCellsExceptHeader. But I want to restrict the columns to grow beyond a certain value. There is a MinimumWidth Property ... but unfortunately no MaximumWidth Property.

Any ideas how to solve this?

Thanks in advance, Frank

like image 423
Aaginor Avatar asked Jun 15 '10 13:06

Aaginor


3 Answers

The only way i managed to do that, is to check the columns width after adding rows to it, check the width, and if it's size is above my max, i set it manually after changing the columns AutoSizeMode to DataGridViewAutoSizeColumnMode.None

      foreach(DataGridViewColumn c in myView.Columns)
            if (c.Width > myMax)
            {
                c.AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
                c.Width = myMax;
            }

Naturally, you'd need to set the AutoSizeColumnsMode to AllCellsExceptHeader again when you add/update/delete rows and do the procedure again.

like image 129
Crypth Avatar answered Nov 03 '22 15:11

Crypth


I know it's an older problem, but i faced it myself and got a decent (I guess it is) solution;

' Eventhandler 
Private Sub DataGridView1_ColumnWidthChanged(sender As Object, e As DataGridViewColumnEventArgs)

// If my Grid refreshes this event doesnt work properly so I stop it from firing
    If isRefreshing Then Exit Sub

    Dim col As DataGridViewColumn = e.Column
    If col.AutoSizeMode = DataGridViewAutoSizeColumnMode.None Then //optional
        Dim isWidth As Integer = col.Width
        Dim prefWidth As Integer = col.GetPreferredWidth(DataGridViewAutoSizeColumnMode.AllCellsExceptHeader, True)
        If isWidth > prefWidth Then col.Width = prefWidth
    End If
End Sub

In this case my MaxWidth is the Prefferred Width. You can change prefWidth to whatever maximum you want.

like image 29
Luke Avatar answered Nov 03 '22 16:11

Luke


My version is

private const int GridAutoResizeBoundary = 100;
private const int MaxColumnWidth = 300;

public static void AutoSizeColumns(this DataGridView dataGridView)
{
    if (dataGridView.RowCount <= GridAutoResizeBoundary)
        dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
    else
        dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells);

    foreach (DataGridViewColumn column in dataGridView.Columns)
    {
        if (column.Width > MaxColumnWidth)
            column.Width = MaxColumnWidth;
    }
}
like image 1
Mike Avatar answered Nov 03 '22 15:11

Mike