So you'd like to use a Repeater control for their ease of HTML formatting over an DataGrid or perhaps you're just nostalgic of coding looping table rows from a database, but you need to have the functionality of the "Select Command" button that the DataGrid control offers.
Phear not, you can create any number of columns with functional LinkButtons that can be tied to protected methods on the code behind page. Here's how...
The HTML Part...
First, within your repeater, choose where you're link column will be. In this example it's the first column. Note the LinkButton tags. Simply replace the data elements shown here. OnCommand will be the name of the c# function that will handle the click. CommandArgument will contain the unique identifier for your data, or whatever data element you want to pass back to your function to aid in processing. Finally, the text between LinkButton tags will contain whatever text, or data element you want displayed as the link, in this case the data field 'Name'. Additionally, we're giving the link a unique name by appending the 'SerialNo' column to 'EditLink' creating values like EditLink1, EditLink5, etc.
<table>
<tr>
<th>Name</th>
<th>Rank</th>
</tr>
<asp:Repeater id="Repeater1" runat="server">
<ItemTemplate>
<tr style="background-color:whitesmoke;">
<td>
<asp:LinkButton ID="lnkEditItem" Runat="server" OnCommand="EditItemClick"
CommandArgument='<%# DataBinder.Eval(Container.DataItem, "serialno") %>'
CommandName='EditLink<%# DataBinder.Eval(Container.DataItem, "serialno") %>'
><%# DataBinder.Eval(Container.DataItem, "name") %></asp:LinkButton>
</td>
<td><%# DataBinder.Eval(Container.DataItem,"rank") %></td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
The C# part...
So you have a unique set of link buttons which are calling a c# method, and passing the 'SerialNo' field value. Now we need to create the c# function that will handle the click, read the passed value and do something with it. So in the code behind, you'll need something like this.
Note the method must be of type protected and have a signiture matching the one below in order for it to receive the click from the link button.
protected void EditItemClick(Object sender, CommandEventArgs e)
{
// Get the SerialNo value passed
string thisid = e.CommandArgument.ToString();
// Do something with the value
DisplayRecord(thisid);
return;
}
Conclusion
So in conclusion here's a simple way to add dynamic button functionality to a repeater control that can ultimately create a table with clickable link for each record.
Please note that you can use this method to add as many link columns as you want to your table. For example if you want a 'Delete' button, create another column within your repeating section containing a LinkButton. You must assign it to a new C# method, give the links unique CommandNames, but do the same passing the value you need for the operation you want to perform, create the function and you're set.
