|
private
void AutoSizeCol(int colIndex)
{
DataTable tbl =dataGrid1.DataSource as DataTable;
int rowCount =tbl.Rows.Count;
if (0!=rowCount)
{
//Gets a new Graphics object from the handle of the datagrid window
Graphics g =Graphics.FromHwnd(dataGrid1.Handle);
StringFormat sf =new StringFormat(StringFormat.GenericTypographic);
SizeF headerSize;
string headerText=dataGrid1.TableStyles["Customers"].GridColumnStyles[colIndex].HeaderText;
//the param value for maximum layout area is an approximation
//You can play around with this if the grid is not autosizing correctly
//That is you can increase it and see the effects
headerSize=g.MeasureString(headerText,dataGrid1.Font,500,sf);
//Check the sizes of the column data
Single width=0;
SizeF dataSize;
for(int rowIndex=0;rowIndex<rowCount; rowIndex++)
{
string colData =dataGrid1[rowIndex,colIndex].ToString();
dataSize=g.MeasureString(colData,dataGrid1.Font,500,sf);
if(dataSize.Width >width)
{
width=dataSize.Width;
}
}
//This is used for taking care of leading and trailing padding of the text field
//You can experiment with it to find the right padding factor for your tables.
int paddingFactorHeader =10;
int paddingFactorData=10;
//f the width of the header is less than the Maximum Column Data width then use
//
Max
Column
Width
//Else
//Use the width of the column header
if(headerSize.Width <width)
{
dataGrid1.TableStyles["Customers"].GridColumnStyles[colIndex].Width =Convert.ToInt32(width) + paddingFactorData;
}
else
{
dataGrid1.TableStyles["Customers"].GridColumnStyles[colIndex].Width=Convert.ToInt32(headerSize.Width) + paddingFactorHeader;
}
g.Dispose(); //Release this resource
}
}
|