I often find when using templated data-bound controls (in either ASP.NET 1.1 or 2.0) that my expressions become rather difficult to understand because of the need to fit all of your logic into a single expression. For example, I have seen databound expressions that look something like:
<asp:TemplateField HeaderText="SomeColumn">
<ItemTemplate>
<%# ((bool)Eval("foo")) ? Eval("bar") : (((bool)Eval("quux")) ? Eval("a") : Eval("b")) %>
</ItemTemplate>
</asp:TemplateField>
Which is even worse in 1.1 because each Eval must be replaced with DataBinder.Eval(Container.DataItem, "xx"). There are also occasions where you just can't compress all the logic you need to into a single expression. An alternative, which I find myself using quite a bit, even when developing in 2.0, is to write a single method in your code behind class to generate the desired string. Have it take an object reference (which will be the bound row) and take as many lines as you like to construct the string to be generated in the template. Here's a method that returns the same string as the overly-complex expression above:
protected string GenerateFooString(object dataItem)
{
bool foo = (bool)DataBinder.Eval(dataItem, "foo");
bool quux = (bool)DataBinder.Eval(dataItem, "quux");
string ret = string.Empty;
if (foo)
ret = (string)DataBinder.Eval(dataItem, "bar");
else if (quux)
ret = (string)DataBinder.Eval(dataItem, "a");
else
ret = (string)DataBinder.Eval(dataItem, "b");
return ret;
}
And the simplified template now looks like:
<asp:TemplateField HeaderText="SomeColumn">
<ItemTemplate>
<%# GenerateFooString(Container.DataItem) %>
</ItemTemplate>
</asp:TemplateField>
Posted
Dec 16 2005, 07:43 AM
by
fritz-onion