I’ve been tasked at work with creating a dashboard in Flex that enables users to turn on and off Key Performance Indicators (KPIs). The main display is a DataGrid. The concept is simple enough. As the user checks which KPIs they want to see, the DataGrid will set the visible property of the specific column to true, and false if that KPI is unchecked. A problem appears with column widths, however. Flex likes to decide for you how wide each column should be given the area it has to work with. Sometimes, the decision is really bad, especially if the user has already resized columns, then adds a new column.
This dashboard also needs to be able to save the user’s KPI choices and column orders, then be able to redisplay data each time they log in and use the dashboard, all with their column order and pre-selected KPIs displaying nicely with the column widths they set previously.
Easy, right?
Well, not so much. After many hours of trying to get it working the way I want, I took another hard look at the Flex documentation. I found the key was in the horizontalScrollPolicy setting. You see, I really wanted to have a horizontal scroll bar only if necessary. I tried setting horizontalScrollPolicy to “auto”, but that just wasn’t reliable. In fact, the horizontal scroll bar was always on. So, I started managing the horizontal scroll bar myself by checking the widths of all the visible columns in the DataGrid. If the widths were less than my DataGrid size, I would set the horizontalScrollPolicy to “off”, otherwise, it would be “on”.
A funny thing happens when the horizontalScrollPolicy is “off”. It makes sense . . . sort of. Column widths are largely ignored if the horizontalScrollPolicy is “off”. The reason for this is because the DataGrid needs to readjust all the columns to fit within the DataGrid width. It doesn’t matter if you set the widths if the invisible columns to 0, either. These get assigned a width (though that seems like a bug to me). So, say you have 25 columns, but only want to display 6, and have them laid out nicely with pre-determined widths. How do you do this without having the DataGrid control mangle it up?
The answer is actually quite simple. Before setting any column widths, set the horizontalScrollPolicy to “on”. Then, set your widths. Set the widths of all the invisible columns to 0, and your visible columns to your desired widths. Then, set the horizontalScrollPolicy to your desired setting (“off”, if you don’t want a scroll bar).
