Saturday, February 10, 2007

Resizing columns to fit in a DataGrid

I wanted to automatically set the width of columns in a WinForms DataGrid to something sensible based on the contents (using .NET 1.1 for a number of reasons). I've seen the solution to this in a couple of places but they didn't work for me because I'm using a grid that inherits from DataGrid and adds a few helper methods. So here's what I've come up with.

    public void AutosizeColumns()
      Type t = GetType();
      t = t.BaseType;
      MethodInfo m = t.GetMethod("ColAutoResize", BindingFlags.Instance  BindingFlags.NonPublic);

      for (int i = 0; (i < TableStyles[0].GridColumnStyles.Count); i++)
        m.Invoke(this, new object[]{i});

No comments: