I\'m trying to set the width of the columns in my datagrid. I use Compact Framework 2.0 and C#
I tried this but it gives me an \"out of bonds\" error message:
<
DataGrid is now obsolete but I encountered the same problem when changing some legacy code so I'll post my solution.
The problem is that DataGrid has a private field called myGridTable that is holding the current DataGridTableStyle. A current DataGridTableStyle exists even if the TableStyles collection is empty, in which case it points to a default DataGridTableStyle which is also private/internal.
Since DataGrid is obsolete anyway and won't be changed, I decided to just use Reflection to access those private fields. They should have been public anyway and making them private was a bad design decision IMO.
The advantage of working with the current styles directly is you don't need to destroy and recreate the table styles just to change the widths, and it works without unexpected behavior every time.
I created a few extension methods to do it:
static class DataGridColumnWidthExtensions
{
    public static DataGridTableStyle GetCurrentTableStyle(this DataGrid grid)
    {
        FieldInfo[] fields = grid.GetType().GetFields(
                     BindingFlags.NonPublic |
                     BindingFlags.Instance);
        return (DataGridTableStyle)fields.First(item => item.Name == "myGridTable").GetValue(grid);
    }
    public static IList GetColumnWidths(this DataGrid grid)
    {
        var styles = grid.GetCurrentTableStyle().GridColumnStyles;
        var widths = new int[styles.Count];
        for (int ii = 0; ii < widths.Length; ii++)
        {
            widths[ii] = styles[ii].Width;
        }
        return widths;
    }
    public static void SetColumnWidths(this DataGrid grid, IList widths)
    {
        var styles = grid.GetCurrentTableStyle().GridColumnStyles;
        for (int ii = 0; ii < widths.Count; ii++)
        {
            styles[ii].Width = widths[ii];
        }
    }
}