Best Practices for Using Conditional Formatting in Data Binding Controls?

I have a relay linked to a custom entity (EntitySpaces request) and noticed that there are several ways to conditionally format the displayed values.

1) From my aspx, I can call a method in my code lag and pass the associated value and use it to control any conditional logic:

        <a class="star" href="<%#MakePackageSelectionUrl((int)DataBinder.Eval(Container.DataItem, "PackageId"))%>">

and then in the code-dehind:

    protected string MakePackageSelectionUrl(int packageId)
    {
              return string.Format("/Packages/NoAjax/ToggleStar.aspx?p={0}&amp;s={1}&amp;st={2}", packageId, _streamId, (int)_phase);
    }

      

2) I can hook into the ItemDataBound event, get the e.Item.DataItem as a DataRowView, and then go crazy:

    protected void PackageList_ItemDataBound(Object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) { return; }

        DataRowView details = (DataRowView)e.Item.DataItem;

        EncodePackageName(e, details);
        EncodeStatusName(e);
        DisplayStarImage(e, details);
    }

    private static void EncodePackageName(RepeaterItemEventArgs e, DataRowView dr)
    {
        HtmlAnchor p = (HtmlAnchor)e.Item.FindControl("packageLink");
        if (p != null)
        {
            p.HRef = string.Format("/Packages/View.aspx?p={0}", dr["packageId"]);
            p.InnerHtml = HttpUtility.HtmlEncode((string)dr["packageName"]);
        }
    }

      

I also noticed that using e.Item.FindControl () in code requires runat = "server" on the aspx control, which has the nasty habit of encoding ids and messing up HTML altogether.

I really want to hear from everyone who has come up with a good approach to solving such problems.

+1


source to share


2 answers


In this case, all you are doing is manipulating some HTML, so I would use the first method. The second method comes in handy when you need to check that the item is bound to the database and make changes to the server controls in response (for example, bind nested lists).

Note also that calls to DataBinder.Eval () are expensive - it uses reflection. You will get better performance using explicit casting:



MakePackageSelectionUrl(((System.Data.DataRowView)Container.DataItem)["PackageId"])

      

For reference: http://msdn.microsoft.com/en-us/library/ms998549.aspx . See the section on Minimizing Calls in DataBinder.Eval.

+1


source


Keep it simple.

The more code you write (even if it is repeated), the more bugs can enter.



I prefer the first method as you don't need an event handler and keep all of your formatting in a separate class if used more than once.

+1


source







All Articles