Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

Repeater Web Server Control - Conditional Logic?

I see tons of samples all illustrating how to use the repeater control to display the contents of a dataset, however I'm having a difficult time finding any examples that demonstrate how to modify the output of a template based upon the data.

Some examples of what I'm trying to accomplish would be to conditionally display particular labels based upon whether the data is present, or even something as replacing 0 with some text such as "None".

Any tips? Thanks!

Colby Makowsky
Friday, July 25, 2003

Two approaches (in C#):

...
<ItemTemplate>
  <%#((int)DataBinder.Eval(Container.DataItem,"ColumnName")) == 0 ? "None" : DataBinder.Eval(Container.DataItem,"ColumnName")%>
</ItemTemplate>
...

or

...
<ItemTemplate>
  <%# MyFormatFunction(Container) %>
</ItemTemplate>
...

and in code behind:

protected string MyFormatFunction(RepeaterItem item)
{
  DataRowView row = (DataRowView)item.DataItem;
  int myValue = (int)row["ColumnName"];
  if(myValue==0)
      return "none";
  else
      return myValue.ToString();
}

You will need to modify the code depending on what you are binding to (a DataSet/Table? a DataReader?) etc.

Duncan Smart
Monday, July 28, 2003

Or, you could change the output in a function wired to the ItemDataBound event:

In VB.Net this time:

On the page:

<asp:Label ID="lblAmount" Runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Amount") %>' />

In the backend code:

Protected Sub repAlerts_ItemDataBound(ByVal sender As _
Object, ByVal e As _
System.Web.UI.WebControls.RepeaterItemEventArgs) _
Handles repAlerts.ItemDataBound
  Select Case e.Item.ItemType
      ' Do this to avoid trying this on
      ' headers/footers/edititems
      Case ListItemType.Item, ListItemType.AlternatingItem
        Dim lblAmount as Label = e.Item.Findcontrol _
            ("lblAmount")
        If (lblAmount.Text = "0") Then
            lblAmount.Text = "None"
        End If
  End Select
End Sub

Greg Hurlman
Wednesday, July 30, 2003

What if you want to bind the ROW to the data.

Eg.

If data = 0 then

do not display entire row

else

display row with data

end

Damir
Monday, August 25, 2003

*  Recent Topics

*  Fog Creek Home