protected void SizeColumns(DataGrid grid)
{
Graphics g = CreateGraphics();
DataTable dataTable = (DataTable)grid.DataSource;
DataGridTableStyle dataGridTableStyle = new DataGridTableStyle();
dataGridTableStyle.MappingName = dataTable.TableName;
foreach(DataColumn dataColumn in dataTable.Columns)
{
int maxSize = 0;
SizeF size = g.MeasureString(
dataColumn.ColumnName,
grid.Font);
if(size.Width > maxSize)
maxSize = (int)size.Width;
foreach(DataRow row in dataTable.Rows)
{
size = g.MeasureString(
row[dataColumn.ColumnName].ToString(),
grid.Font);
if(size.Width > maxSize)
maxSize = (int)size.Width;
}
DataGridColumnStyle dataGridColumnStyle = new DataGridTextBoxColumn();
dataGridColumnStyle.MappingName = dataColumn.ColumnName;
dataGridColumnStyle.HeaderText = dataColumn.ColumnName;
dataGridColumnStyle.Width = maxSize + 5;
dataGridTableStyle.GridColumnStyles.Add(dataGridColumnStyle);
grid.TableStyles.Add(dataGridTableStyle);
g.Dispose();
}
![](https://img2024.cnblogs.com/blog/35695/202408/35695-20240826070647288-243310440.jpg)