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:

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


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.


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

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!

Comments

  1. Anonymous1:13 PM

    In my mind, only solution #2 is valid because solutions #1 and #3 rely on inserting business logic into the presentation layer.

    ReplyDelete
  2. That an interesting "purist" observation. However, it seems to me that all three of the examples "insert business logic into the presentation layer".

    ReplyDelete
  3. Anonymous3:24 PM

    Yes Michael, ALL three break your proposed "11th commandment". But, who really gives a shit?! ROFL

    ReplyDelete

Post a Comment

Popular posts from this blog

FIREFOX / IE Word-Wrap, Word-Break, TABLES FIX

Some observations on Script Callbacks, "AJAX", "ATLAS" "AHAB" and where it's all going.

IE7 - Vista: "Internet Explorer has stopped Working"