This tutorial will demonstrate how add events to buttons within a repeater using ASP.NET 4.0 and C#.

Creating the Web Site

To demonstrate how we can add a button click event to our dynamic buttons within a repeater, we will need to create a simple web site. To do this, create a new ASP.NET Empty Web Site and:

  1. Right click the project in your solution explorer.
  2. Select add new item…
  3. Select a web form.
  4. Name it ‘Default.aspx’.
  5. Click add.
  6. Open Default.aspx up to design mode.
  7. Drag and drop a repeater onto the web form.

Next, we will want to add in a button into the item template of our repeater. To do this, open up Default.aspx to source mode and add the following code to the repeater:

This simply adds a button to the item template while setting two important properties that we will need for our event. The CommandName and CommandArgument properties both get passed to the ItemCommand event method when a button on the repeater is clicked. It is from this method that we can add in functionality for our dynamic buttons. It is important to understand that we can still add an event to this button using the OnClick property, however we don’t have as much control while using that event.

Adding the Events

First, we need to go ahead and add a data source with some data in it to our repeater so that we can view the buttons on our page. For this, I am going to create a data table with one row and bind it to our repeater. To do this, open up the Default.aspx.cs for editing and add the following code to the Page_Load event method:

Next, we need to add some code to our repeater’s ItemCommand event method. In this method we have access to both the command name and argument that we set on our button in the repeater. We can use these values to add conditions to determine what button on our repeater has been clicked, and then add our functionality to this using the command argument if needed. Here is some sample code that you can add to the Repeater1_ItemCommand event method that uses our properties:

This simply outputs the values to the page, and then sets up the condition you would need to bind an event specifically to that button. This method of adding events to our repeater’s buttons is extremely powerful because it gives you control over as many different buttons that you need, while allowing extra data to be passed to the method via the command argument.

Download Source Files