Setting ListView Columns dynamically in Windows Mobile Applications
Hardcoding values into source code is never advised. It is particularly instructive in a windows mobile application as far as one is concerned about the various devices on which windows mobile OS runs. These devices have varied screen sizes and making your application adaptive to each device is definitely a show of good programming.
A good scenario for this is using ListView control to display records. It is easy to set the ListView columns to fit the screen of the Emulator or device you are using for your testing during development. That is called hardcoding. What happens after deployment to other devices? Granted, the ListView horizontal and vertical scrollbar will automatically help with rendering each row of record. But it may not be what you want as users will have to move back and forth unnecessarily. Or it may be needless since the rendering could have been more proper if the columns have been set dynamically.
The .NET GUI controls have Anchor property which can be used to stretch and adapt the ListView size to your device screen size. It is ok if your ListView has only one column. But what if there are 2 or more columns and column width ought to be allocated according to a pre-set ratio?
The code snippet below demonstrates how to dynamically set the columns width of a ListView at runtime. The logic is to allocate a percentage of the ListView control to each column. You can be sure that this logic, along with setting the Anchor property of the control to the right will always give your control a better rendering.
ListView1.Columns.Clear();
float fWidth ;
ColumnHeader colTo = new ColumnHeader();
colTo.Text = "Name";
fWidth = (0.38F * ListView1.Width);
colTo.Width = (int)fWidth;
ColumnHeader colMessage = new ColumnHeader();
colMessage.Text = "Number";
fWidth = (0.55F * ListView1.Width);
colMessage.Width = (int)fWidth;
//add the columns
ListView1.Columns.Add(colTo);
ListView1.Columns.Add(colMessage);
The two columns are allocated 38% and 55% respectively. The remaining 7% is an allowance for Vertical scrollbar so that Horizontal scrollbar will not appear automatically. I personally dislike having both bars on my ListView control.
No comments:
Post a Comment