问题
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
回答1:
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.
回答2:
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.
回答3:
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;
}
}
来源:https://stackoverflow.com/questions/3045805/datagridview-autosize-but-restrict-max-column-size