Tuesday, February 24, 2009

Modifying datagrids without using DataGrid_ItemDataBound

A common requirement in most of our screens

An advantage in the second case is that because you’re using a .Net literal control, the cell will maintain its value across post-backs You can code to specific conditions by varying the implementation of returnComparisonBool()

<!-- For an image -->
<asp:TemplateColumn HeaderText=”Physical Location” ItemStyle-HorizontalAlign=”Center” ItemStyle-VerticalAlign=”Middle”>
<ItemTemplate>
<a href=”#” onclick=’return launchAddrs(<%#DataBinder.Eval(Container.DataItem,”alt_id”)%>);’>
<asp:Image ID=”Image1” Runat=”server” Visible=’<%#returnComparisonBool(DataBinder.Eval(Container.DataItem,”PHYS_LOC_CD”), “ALT”)%>’ ImageUrl=”../Images/VIEWB.bmp”>
</asp:Image></a>
</ItemTemplate>
</asp:TemplateColumn>
<!-- For an simple string -->
<asp:TemplateColumn HeaderText=”Issued?” ItemStyle-HorizontalAlign=”Center” ItemStyle-VerticalAlign=”Middle”>
<ItemTemplate>
<asp:Literal Runat=server ID=LitIss Visible=’<%#returnComparisonBool(DataBinder.Eval(Container.DataItem,”PHYS_LOC_CD”), “ISS”)%>’>*</asp:Literal>
</ItemTemplate>
</asp:TemplateColumn>

protected bool returnComparisonBool(Object Value, string Expected)
{
return (!((Value == DBNull.Value) || ((string)Value != Expected)));
}

--

Yes, performance-wise there is probably no difference. In fact, the method will get called for every item.

And you can also get the advantage of the literal control even in the DataGrid_ItemDataBound by making it visible / invisible.

The only advantage I saw was that code of each condition checking can be logically separated (not in this case) instead of being in one event handler (ItemDataBound).

And there’s also need to access the bound object again since you’ll get the data you need in the binding itself.

And of course, no need for using FindControl / Datagrid.cells.

No comments:

Post a Comment