Conditional logic inside repeaters

November 9, 2006

Today I was trying to make some asp:Labels visible or not based on what kind of data the repeater was showing, ie having som kind of if-else-clause to decide what to show.

That wasn’t as easy as I thought, and I saw that many people had had the same problem when googling this question at Google Groups.

The solution for me was to add an OnItemDataBound property to the repeater, like this:

OnItemDataBound="Repeater1_ItemDataBound"

And then, in the codebehind file I added an event handler.

protected void Repeater1_ItemDataBound(Object sender, RepeaterItemEventArgs e)

Inside that event handler I simply added the conditional logic for showing or not showing the stuff I wanted to.


  bool visibility;
 
  if(Condition)
  {
            visibility = true;
  }
  else
  {
            visibility = false;
  }
 
  ((Label)e.Item.FindControl("lblLabelName")).Visible = visibility;

That did the trick for me, hope it helps you.

2 Responses to “Conditional logic inside repeaters”

  1. lwatts Says:

    My appreciation. Found this article from the Google search “code C# Repeater logic”. Exactly what I needed.

    To add to this, I needed to make sure the current row wasn’t a Header or Footer, then check if this DataSource’s column_id value matched the user’s selection.

    if (e.Item.ItemType.ToString() == "Item" || e.Item.ItemType.ToString() == "AlternatingItem")
    {
        //For displaying comments, check to see if this line is the same as the comment id.
        if (Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "DB_Comment_ID")) == iCommentID)
            ((Literal)e.Item.FindControl("litRepeaterRowType")).Text = "";
        else
            ((Literal)e.Item.FindControl("litRepeaterRowType")).Text = "";
    }
    

    Note: I have a literal named litRepeaterRowType where a is expected to be placed at the start of each repeater row. This causes my selected row to highlight yellow. ( >.< thank you microserf)

  2. lwatts Says:

    The html within the code and comment above was removed. The first literal is set to [tr class=\”selectComment\” style=\”background-color:Yellow;\”]
    The second literal to [tr]
    And in the Note below the code “litRepeaterRowType where a [tr] is expected”
    All with html brackets instead.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: