public class DataGrid列自适应
{
public DataGrid列自适应()
{
}
static public void SizeColumnsToContent(DataGrid dataGrid, int nRowsToScan)
{
Graphics mGraphics = dataGrid.CreateGraphics();
DataGridTableStyle tableStyle= new DataGridTableStyle();
try
{
DataView dataView = (DataView)dataGrid.DataSource; //我是和DataView帮定的
if(nRowsToScan == -1)
{
nRowsToScan = dataView.Count;
}
else
{
nRowsToScan = System.Math.Min(nRowsToScan, dataView.Count);
}
dataGrid.TableStyles.Clear();
tableStyle.MappingName = dataView.Table.TableName;
DataGridTextBoxColumn columnStyle;
int iWidth;
for(int iCurrCol = 0; iCurrCol<dataView.Table.Columns.Count; iCurrCol++)
{
DataColumn dataColumn = dataView.Table.Columns[iCurrCol];
columnStyle = new DataGridTextBoxColumn();
columnStyle.TextBox.Enabled = true;
columnStyle.HeaderText = dataColumn.ColumnName;
columnStyle.MappingName = dataColumn.ColumnName;
iWidth = Convert.ToInt32(mGraphics.MeasureString(columnStyle.HeaderText, dataGrid.Font).Width);
DataRowView dataRow;
for(int iRow = 0; iRow<nRowsToScan; iRow++)
{
dataRow = dataView[iRow];
if (dataRow[dataColumn.ColumnName] != null )
{
int iColWidth = Convert.ToInt32(mGraphics.MeasureString(dataRow[iCurrCol].ToString(), dataGrid.Font).Width);
int iColHight = Convert.ToInt32(mGraphics.MeasureString(dataRow[iCurrCol].ToString(), dataGrid.Font).Height);
iWidth = Convert.ToInt32(System.Math.Max(iWidth, iColWidth));
}
}
columnStyle.Width = iWidth + 10;
tableStyle.GridColumnStyles.Add(columnStyle);
}
dataGrid.TableStyles.Add(tableStyle);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
mGraphics.Dispose();
}
}
}
这个是网上一个VB代码改的 我代码里的DataGrid是和DataView数据帮定的 如果你是和DataTable帮定的话就改一下