Jeffrey Palermo (.com)

Sponsors

The Lounge

News

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Named DataGrid columns - wouldn't it be nice? - level 300

Earlier, I blogged about using controls that are embedded in unusual places in the control tree of the DataGrid.  For instance, putting a LinkButton for adding a new record in the header or footer of the DataGrid.  You have to manually manipulate the Controls collection to do this. 

Another issue is what if you put that LinkButton in the same column as the Edit, update, cancel, delete buttons?  If you want to restrict editing of the data, a step on the UI would be to hide that entire column.  Seems pretty straight-forward, but how do you get a reference to that column?  I searched, and the only way I found was to reference it by the index in the Columns collection:

dgd.Columns[7].Visible = false;

That works well, but it bit me in the butt when I tried to maintain that code.  Down the road it became necessary to add two columns to that DataGrid.  Then, you guessed it!  A nice, little bug in my code.  Usually I'm able to avoid the debugger in VS by writing modular code and using the heck out of the ASP.NET Trace feature (great for code maintenance), but this was an issue that actually required a breakpoint.  Once inside the code, it was very clear what was happening.  I changed the index to the new index of the edit column, and my problem was fixed (until next time), but isn't there a more maintainable way to do this?  What happens when another developer needs to modify my application.  Yeah, I document the heck out of it, but why can't the Columns collection support column name identifiers as well.  I know the answer (CollectionBase), but it would be nice.

For now, I'll have several lines of comments above that code. 


Posted 08-24-2004 5:52 AM by Jeffrey Palermo

[Advertisement]

Comments

Richard Wan wrote re: Named DataGrid columns - wouldn't it be nice? - level 300
on 10-08-2004 10:58 AM
I know this is bad form but: ditto, me too, I agree
m@ wrote re: Named DataGrid columns - wouldn't it be nice? - level 300
on 02-28-2005 2:53 AM
I used an enumeration to solve this problem. Everywhere that I need to reference a datagrid column index, I reference the enum name. You still have to make sure the enum order matches the order of columns in the datagrid but at least you only have to maintain it in one place.
Jeffrey Palermo wrote re: Named DataGrid columns - wouldn't it be nice? - level 300
on 04-18-2005 4:45 PM
You can also do something hacky with the dataset that is bound to the datagrid .. if your columns are straight from the datagrid you can use the index by name feature of the dataset to get the appropriate index (using .Ordinal) and then map that into the index of your datagrid column