How do I do conditional logic within an ASP.NET DataRepeater control?

Christopher Jon Mankowski picture Christopher Jon Mankowski · Aug 12, 2010 · Viewed 8.8k times · Source

I'm binding my DataRepeater control to a table that has many columns. I'd like to only display a subset of those, depending on what is populated.

How/where should I do my contitional tests within a dataRepeater? This is the code within my itemtemplate:

<% if (0= (DataBinder.Eval(Container.DataItem, "first").ToString().Length))
{
   i++;
}
    %>

The error I get is: CS0103: The name 'Container' does not exist in the current context

Answer

samandmoore picture samandmoore · Aug 12, 2010

You should be fine with this:

<% if (0 == (Eval("first").ToString().Length))
{
   i++;
}
%>

But depending on what you want to do, I would probably write a function to handle the binding of the data in order to retain separation between display and business logic.

e.g.

in your aspx:

<asp:Repeater id="myRepeater" runat="server" onDataItemBound="FillInRepeater">
<ItemTemplate>
<div class="contactLarge">
    <div style="background-color:#C5CED8;clear:both"><asp:Label runat="server" ID="title"></asp:Label>
    .
    .
    .
</div>
</ItemTemplate>
<AlternatingItemTemplate>
</AlternatingItemTemplate>
</asp:Repeater>

in your code-behind:

protected void FillInRepeater(object sender, RepeaterItemEventArgs e)
{
  if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
  {
    //in here you bind to your repeater labels and stuff then do all that sorta logic.
    //Grab Primary Data
    string titleText = DataBinder.Eval(e.Item.DataItem, "title").ToString();
    string somethingElseText = DataBinder.Eval(e.Item.DataItem, "somethingElse").ToString();
    string maybeSeeMaybeDontText = DataBinder.Eval(e.Item.DataItem, "maybeSeeMaybeDont").ToString();

    //Find the controls and populate them according the to row
    Label titleLabel = (Label)e.Item.FindControl("title");
    Label somethingElseLabel = (Label)e.Item.FindControl("somethingElse");
    Label maybeSeeMaybeDontLabel = (Label)e.Item.FindControl("maybeSeeMaybeDont");

    // display the fields you want to
    titleLabel.Text = titleText;
    somethingElseLabel.Text = somethingElseText;

    // here is where you could do some of your conditional logic
    if (titleText.Length != 0 && somethingElseText.Length != 0)
    {
        maybeSeeMaybeDontLabel.Text = maybeSeeMaybeDontText;
    }
  }
}

personally, I prefer to do things this way rather than doing any logic inside the ASP. I know that it might seem a bit silly to some people, but I like to keep my business logic separate from my display logic whereever possible.