Back in November, I got around to using Scott's cool routine for resizing DataGrid columns automatically. Now that I'm using it more often, I decided I wanted to make it a little more generic so that I didn't have to rewrite it for each DataGrid that I used it on.
With a simple change to using the 'sender', I no longer need to do any editing. Drop it in and wire it up! it's ready to go.
/// <summary>
/// Automatically resize the columns of a DataGrid to fit the
/// data within
/// </summary>
/// <param name="sender">The DataGrid that needs resizing</param>
/// <param name="e"></param>
private void DataSourceChanged( object sender, System.EventArgs e )
{
try
{
Type t = sender.GetType();
MethodInfo m = t.GetMethod( "ColAutoResize", BindingFlags.NonPublic
| BindingFlags.Instance );
for( int i = ( (DataGrid) sender ).FirstVisibleColumn;
( i < ( (DataGrid) sender ).VisibleColumnCount ); i++ )
{
m.Invoke( sender, new object[] {i} );
}
}
catch( Exception ex )
{
System.Diagnostics.Trace.Write( "Failed Resizing Columns: "
+ ex.ToString() );
}
}