//========================================================================================== /// <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; }
|