Friday, June 20, 2008

Dynamically Add and Modify Server Side Buttons in an ASP.NET Datagrid or Repeater

Within the last few weeks I was asked about how to dynamically format the output of either datagrids or repeater objects in .Net. My response at the time was to do something like the following:

<%# SomeMethod(DataBinder.Eval(DataItem.Container, "data_column").ToString()) %>

Where SomeMethod() is a server-side method in the code-behind which evaluates the bound-data given to it as a parameter, and returns it in the desired format. In some code that I've used this design, I send SomeMethod, which is called DateFormatter() in my code, two dates and then compare the two dates to see if they are the same. If they are the same then the method returns just the one date in MM/DD format, but if they are different then the method returns the two dates like so, MM/DD - MM/DD.

Recently I found that I had need for something a little bit more robust. I wanted to dynamically create server-side buttons in the repeater object which would have different parameters based on the data to which the item was bound. To do this I created a method and wired it to the OnItemDataBound Event of the Repeater. Here is basically what I did:

Aspx File

<asp:Repeater OnItemDataBound='ItemDataBoundMethod'>
...
<ItemTemplate>
<input type='hidden' id='parameter1' value='<%#DataItem.Container, "data_column").ToString())' runat="server" />
... Some More Hidden Fields ...
<!-- Below I create a button with no parameters and no events wired to it, so that I can set them dynamically in the OnItemDataBound Event-->
<asp:Button id='ButtonTemplate' runat='server' />
</ItemTemplate>
...
</asp:Repeater>




Code-Behind

protected void ItemDataBoundMethod(Object sender, RepeaterItemEventArgs e)
{
//Make sure that this is an item and not a header, footer, etc.
if(e.Item.ItemType == ListItemType.Item e.Item.ItemType == ListItemType.AlternatingItem)
{
//Here I access the hidden fields with the Id that I gave them
string param1 = ((HtmlInputHidden)e.Item.FindControl("parameter1")).Value.ToString().Trim();
...
Button buttonTemplate1 = ((Button).e.Item.FindControl("ButtonTemplate"));
...
...Evaluate the values in the hidden field and then set the properties of the button accordingly...
...
}
}

1 comment:

Anonymous said...

Awesome. This is exactly what i needed. It would be nice if your code was formatted better on the page though.