In .NET 4.5.1, there is a method to resize columns of DataGridView,
dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.Fill) 'Here datagridView is the Name of DataGridView Control
But I need to do it in .NET 3.5(I need it for Compact Framework which is not supported in .NET framework. So please don't recommend using newer versions). So is there any way to do that in .NET Framework version 3.5?
This worked on .Net 7.0 (C# VS2022).
This will resize the columns of the DataGridView according to their contents automatically.
Don't forget to right-click on the Project and select Sync Namespace to update the namespace according to your project.
namespace DiscountCard.View.CustomControl
{
public partial class CtechDataGridView : DataGridView
{
public CtechDataGridView()
{
InitializeComponent();
DoubleBuffered = true;
}
protected override void OnDataBindingComplete(DataGridViewBindingCompleteEventArgs e)
{
try
{
base.OnDataBindingComplete(e);
// the column width adjusts to fit the contents of all cells in the column, including the header cell.
for (int i = 0; i < this.Columns.Count; i++)
{
if (this.Columns[i].ValueType.Name != "ICollection`1")
{
this.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
}
}
// adust minimum width
int totalColumnWidth = 0;
for (int i = 0; i < this.Columns.Count; i++)
{
DataGridViewColumn column = (DataGridViewColumn)this.Columns[i];
if (column.Visible)
{
int columnWidth = column.Width;
if (i == 0)
{
columnWidth = 120;
}
else if (i > 0)
{
if (columnWidth < 150)
{
columnWidth = 150;
}
}
// the column width does not automatically adjust.
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
column.Width = columnWidth;
column.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
totalColumnWidth += columnWidth;
}
}
// fill last column when total column width < datagridview width
if (this.Columns.Count > 0 && totalColumnWidth < this.Width)
{
this.Columns[this.Columns.Count - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
this.ClearSelection();
}
catch (Exception ex)
{
Log.Exception(ex);
}
}
}
}
Result:
1. The content is longer than the width of the DataGridView.
2. The content is shorter than the width of the DataGridView.