Monday, June 22, 2009
ASP.NET Repeater is a great control to display a series of data in a custom formatted style. It gives you independence to choose your data layout rather than going with the standard table layouts of the DataGrid. When using repeaters it may be sometimes useful to modify a display control inside a repeater depending on the value of a DataItem which is bound to the repeater.
Here's a simple example on how to change value of a control in the repeater on ItemDataBound. The following code checks the value of the "id" column of the DataRow and checks if it matches with the one passed by query string. If that's the case it then updates a Label for that element.
' VB.NET:
Protected Sub rptr_ItemDataBound(ByVal source As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptr.ItemDataBound
If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
If ((CType(e.Item.DataItem, System.Data.DataRowView)).Row("id").ToString() = Request.QueryString("id")) Then
CType(e.Item.FindControl("lblBoolDisplat"), Label).Text = "This value is being requested."
End If
End If
End Sub
// C#
protected void rptr_ItemDataBound(object source, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
if ((e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem))
{
if ((((System.Data.DataRowView)e.Item.DataItem).Row("id").ToString() == Request.QueryString("id")))
{
((Label)e.Item.FindControl("lblBoolDisplat")).Text = "This value is being requested.";
}
}
}
For C#, also add:
OnDataItemBound="rptr_ItemDataBound"on the <asp:Repeater> tag in the ASP.NET page.
Though this is a very simple example, it is very useful in handling complex data. A similar logic is applied when nesting repeaters in a repeater. A nested repeater could be accessed as a nested control in the same way the label is being accessed in the above code.