# Monday, 08 November 2004

Once again, Scott Hanselman has come through for me. For our latest project in Patrick's Web Service class, we are building an application with a DataGrid. It always makes me crazy when using this control that there isn't an automatic “Size Columns Correctly” check box.

Fortunately, I recalled that Scott had found that same frustration and had found the solution. Using a little bit of the Reflection namespace, he grabs the private method that is used when double-clicking on the column borders and fires it off “by hand” for each column.

It's cool and is placed here for posterity.

     1: private void MyDataGridControl_DataSourceChanged( object sender,
     2:                                                   System.EventArgs e )
     3: {
     4:     try
     5:     {
     6:         Type       t = this.myDataGridControl.GetType();
     7:         MethodInfo m = t.GetMethod( "ColAutoResize",
     8:                                     BindingFlags.NonPublic
     9:                                     | BindingFlags.Instance );
    10:  
    11:         for( int i = this.myDataGridControl.FirstVisibleColumn;
    12:                 ( i < this.myDataGridControl.VisibleColumnCount );
    13:                 i++ )
    14:         {
    15:             m.Invoke( this.myDataGridControl, new object[] {i} );
    16:         }
    17:     }
    18:     catch( Exception ex )
    19:     {
    20:         System.Diagnostics.Trace.Write( "Failed Resizing Columns: "
    21:                                         + ex.ToString() );
    22:     }
    23: }
Monday, 08 November 2004 14:09:15 (Pacific Standard Time, UTC-08:00)  #    Comments [0]Tracked by:
Rich "The Hubbins" Claussen [Trackback]
Comments are closed.