Hi all,
I'm using the GridState, and in particular, the GridColumnStates, to restore user-defined column sizes when getting back to a page that contains a grid.
While it's cool that a state can easily be retrieved and set, what I dislike about it is that column widths are treated in absolute sizes (pixels) instead of relative (%). When a state is restored to a different overall resolution (affecting the grid's width), the pixel sizes may not be appropriate.
However, I found out that the Width property is a string, and will also accept ratios when setting the state. I'm persisting the per-grid column configuration in JSON, so this bit of code now takes care of creating the JSON document for me, changing the pixel widths per column by the respective percentage ratio:
public static string GetGridColumnStateJsonScaled<T>(TelerikGrid<T> grid)
{
var gridTotalWidth = grid.GetState().TableWidth;
var states = grid.GetState().ColumnStates;
if (gridTotalWidth.EndsWith("px"))
{
var gridWidthPx = decimal.Parse(gridTotalWidth, CultureInfo.InvariantCulture);
if (gridWidthPx != 0)
{
foreach (var state in states.Where(_ => _.Width.EndsWith("px")))
{
var colWidthpx = decimal.Parse(state.Width, CultureInfo.InvariantCulture);
var ratio = Math.Round(colWidthpx * 100 / gridWidthPx, 3);
state.Width = ratio.ToString(CultureInfo.InvariantCulture) + "%";
}
}
}
var json = JsonSerializer.Serialize<ICollection<GridColumnState>>(states);
return json;
}
The code presumes that the grid width (drawn from the grid's current state) is pixels - usually that should be the case. Also, it will only recalculate columns whose width is also specified with a "px" unit. It will overwrite the original width value inside the state.
This needs to be used whenever a state is about to be persisted as column sizes will be all pixels again as soon as the user modifies anything that affects the state.
While this does work, there might be a more elegant solution that I missed. In case there is not, feel free to use the code above :)
Cheers,
Joe
