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: }
© Copyright 2008 Rich Claussen Theme design by Bryan Bell / Rich Claussen newtelligence dasBlog 1.9.7174.0 | | Page rendered at Thursday, November 20, 2008 3:31:37 AM (Pacific Standard Time, UTC-08:00) Reset | BlogXP | business | calmBlue | candidBlue | Candid Blue Real | dasBlog | dasblogger | DirectionalRedux | Discreet Blog Blue | Elegante | essence | Just Html | MadsSimple | Mobile | Mono | Movable Radio Blue | Movable Radio Heat | nautica022 | orangeCream | Portal | Project84 | Project84Grass | Slate | Sound Waves | Tricoleur | useit.com | Voidclass2