Wednesday, March 16, 2011

ITemplate and DataGrid Column in Codebehind

I have a situation where I need to work with a datagrid and adding columns dynamically in PageInit as the grid has a few conditional requests that it must handle. I'm moving along easily with BoundColumns, and ButtonColumns, those are easy. The problem is with the creation of a TemplateColumn via code. I have found examples out there about creating a custom class that add controls dynamically by creating a class that uses an implementation of ITemplate. That works, however, I'm struggling with how to databind elements.

In my grid I would have used <%= DataBinder.Eval(Container.DataItem, "MyValue") %> or similar, but that isn't an option here. The Container when inside ITemplate doesn't have a data item property either, so I can't bind there. Anyone have advice or links that might help, I'm just not finding the right things in google.

From stackoverflow
  • You can attach an event handler to the DataBinding event of the controls you create in ITemplate.InstantiateIn as in this MSDN Article. The sender will be the control and the NamingContainer property will be the DataGridItem, which has a reference to the DataItem which you can use to get whatever data you need.

    Mitchel Sellers : Awesome! That is the article I was looking for. What a major PITA to get this done....

0 comments:

Post a Comment