Nancy Street Autosize DataGrid Columns
Click to see the Site Map
HomeInfoMusicGalleryPetsGeoHobbiesGeo
Site MapWhat's NewRecent ChangesContactsServer StatisticsSite Information Home « Computers « DevBlog

Back to: Development Blog Contents

A sample method that autosizes the columns of a DataGrid to fit the longest values.

August 2006 Note - The following code is mostly redundant now that the DataGridView control has arrived with the .NET 2.0 Framework. The DataGridView has comprehensive features for adjusting columns widths by content, percentage or fixed values. It's a wonderful new control that contains almost all of the features that were exclusive to expensive commercial grids (all you're missing are splits and heirarchical views). The old DataGrid control can now be regarded as a bad memory.

//==========================================================================================
/// <summary>
/// Auto-sizes the column widths of a DataGrid to fit the longest value.
/// </summary>
/// <remarks>The code is based upon a <a href="http://www.sellsbrothers.com/news/showTopic.aspx?ixTopic=1060">
/// blog article</a> by Chris Sells, but we update the existing column styles directly without
/// the bother of creating new ones. Columns that area already zero width are skipped and
/// remain hidden.</remarks>
/// <param name="grid">The DataGrid to process.</param>
/// <param name="pad">An additional width padding in pixels.</param>
public static void AutoSizeGrid(DataGrid grid, int pad)
{
if (grid == null)
return;
if (grid.DataSource == null)
return;
IList list = null;
if (grid.DataSource is IList)
list = (IList)grid.DataSource;
if (grid.DataSource is IListSource)
list = ((IListSource)grid.DataSource).GetList();
if (list.Count == 0)
return;
PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(list[0]);
string mappingName = GetMappingName(list);
DataGridTableStyle style = grid.TableStyles[mappingName];
if (style == null)
return; // There is no style for the table
using (Graphics g = grid.CreateGraphics())
{
// Outer loop through the columns
for (int i=0; i<pdc.Count; i++)
{
string dispname = pdc[i].DisplayName;
DataGridColumnStyle cs = style.GridColumnStyles[dispname];
if (cs == null)
continue; // No grid column for this value
if (cs.Width == 0)
continue; // The width is zero (leave it hidden)
SizeF maxSize = g.MeasureString(dispname, grid.Font);
SizeF capSize = g.MeasureString(cs.HeaderText, grid.Font);
if (capSize.Width > maxSize.Width)
maxSize = capSize;
// Inner loop through the column's row values
foreach (object o in list)
{
object result = pdc[i].GetValue(o);
string s = pdc[i].Converter.ConvertToString(result);
SizeF size = g.MeasureString(s, grid.Font);
if (size.Width > maxSize.Width)
maxSize = size;
}
cs.Width = Convert.ToInt32(maxSize.Width) + pad;
}
}
} //==========================================================================================
private static string GetMappingName(IList list)
{
if (list is ITypedList)
return ((ITypedList)list).GetListName(null);
else
return list.GetType().Name;
}

Back to: Development Blog Contents


Contact Information | PGP Keys | Site Map | What's New | Visitor Book
Last Updated: 06-Aug-2007 21:11
Copyright © 1999-2007 Orthogonal Programming