GM3TEN
Wed May 10 11:52:34 CDT 2006
intrepid,
Here is some code that may help you.
Regards,
GM
http://nonspect.com
//BEGIN CODE SNIP
/// <summary>
/// Formats the custom column styles to evenly distribute and fill the
entire
/// datagrid display area.
/// </summary>
/// <param name="oGrid">datagrid to format</param>
/// <param name="sTableStyleName">name of the custom table style for
the supplied datagrid</param>
/// <param name="p_blnShowRowHeaders">boolean indicating whether or not
row headers should be displayed</param>
public static void AutoSizeCols(DataGrid oGrid, string sTableStyleName,
bool p_blnShowRowHeaders)
{
if(oGrid.TableStyles.Contains(sTableStyleName) && oGrid.DataSource !=
null)
{
//TODO - This method assumes the DataSource to be a
DataTable...should add defensive code.
DataTable oTable = (DataTable) oGrid.DataSource;
float width = 0;
Graphics g = Graphics.FromHwnd(oGrid.Handle);
StringFormat sf = new
StringFormat(StringFormat.GenericTypographic);
SizeF size = new SizeF(0, 0);
if(oTable != null && oTable.Rows.Count > 0)
{
int numAutoSizedColsTotalWidth = 0;
//process each column style
foreach(DataGridColumnStyle oColStyle in
oGrid.TableStyles[sTableStyleName].GridColumnStyles)
{
//run through each row to get the width of the longest
//text value for the column style we are currently processing...
foreach(DataRow oRow in oTable.Rows)
{
if(oRow[oColStyle.MappingName] != null)
{
if(oRow[oColStyle.MappingName].ToString().Length == 0)
size = g.MeasureString(oColStyle.HeaderText.Trim(),
oGrid.HeaderFont, 500, sf);
else
size =
g.MeasureString(oRow[oColStyle.MappingName].ToString().Trim(),
oGrid.Font, 500, sf);
}
if(size.Width > width)
width = size.Width;
}
oColStyle.Width = Convert.ToInt32(width) + 19;
width = 0;
numAutoSizedColsTotalWidth += oColStyle.Width;
}
//show or hide the row headers here...depends on context
oGrid.TableStyles[sTableStyleName].RowHeadersVisible =
p_blnShowRowHeaders;
int numRowDataWidth = 0;
if(oGrid.TableStyles[sTableStyleName].RowHeadersVisible)
numRowDataWidth = oGrid.ClientSize.Width -
oGrid.TableStyles[sTableStyleName].RowHeaderWidth;
else
numRowDataWidth = oGrid.ClientSize.Width;
//get additional column width to fill entire DataGrid (if
applicable)
int numAdditionalWidth = 0;
if(numAutoSizedColsTotalWidth < numRowDataWidth)
{
numAdditionalWidth = ((numRowDataWidth -
numAutoSizedColsTotalWidth)
/ oGrid.TableStyles[sTableStyleName].GridColumnStyles.Count);
}
//apply the additional width (if applicable)
if(numAdditionalWidth > 0)
{
foreach(DataGridColumnStyle oStyle in
oGrid.TableStyles[sTableStyleName].GridColumnStyles)
{
oStyle.Width = oStyle.Width + numAdditionalWidth;
}
}
oGrid.Refresh();
}
g.Dispose();
}
}
//END CODE SNIP