ASP.NET: Modifying display of DataBound Items based on values of data

"Now you can spend like a drunken liberal on a government grant with our new flat-rate shipping." -- conservative online T-Shirt company

A common question you see on forums and newsgroups is "how to I do xyz with a databound repeater field based on the value of the data?" (e.g. show an image, change the display text, etc.). There are several ways to do this, here are some samples from recent newsgroup posts oriented around the Repeater control:

1. Bound expressions:

<asp:Label runat="server" ID="Label1"
Text='<%# (int) Eval("DataField") > 0 ? "Greater" : "Less or Equal" %>'/>

2. Handling the ItemDataBound event (or RowDataBound for GridView):

protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
RepeaterItem item = e.Item;
if (item.ItemType == ListItemType.Item
item.ItemType == ListItemType.AlternatingItem)
Label label = (Label)item.FindControl("Label1");
DataRow row = ((DataRowView) item.DataItem).Row;
int value = (int) row["DataField"];
label.Text = value > 0 ? "Greater" : "Less or Equal";

3. Call a code-behind method on the bound data.

<asp:Label runat="server" ID="Label1" Text='<%# MyMethod(Container.DataItem) %>'/>

and in the code behind:

protected string MyMethod (object DataItem)
DataRowView dr = DataItem as DataRowView;
if (dr == null)
return "";
return dr["Column1"].ToString() + dr["Column2"].ToString();

Finally, congrats to friend and fellow MVP Stan Schultes on being featured on MVP Insider!