Dynamic Button Using a Repeater« View all ASP.net articles
February 07, 2007
The ASP.net Repeater is a great way to display data without any built-in layout or styles. You have complete control over the layout without the ASP.net engine rendering any tables as with a GridView control.
We will look at how to create a dynamic button using a repeater based on a row data in the repeater's ItemTemplate. Phew, that was a long sentence.
In this example, I have set up a simple repeater, showing the last and first names of all customers from the customer table. After each name, there is a button as well. When the button is clicked, the lblDisplay label displays the id of the customer.
To achive this, I have added the CustomerID to the asp button in the form as well as added the OnClick property to the button.. In the code-behind, I have created a sub procedure called btnRepeat_Clicked that sends the customer id to the lblDisplay label. That was easy!
Form
<form id="frmRepeater" runat="server">
<!--label displays id when button is clicked-->
<asp:Label ID="lblDisplay" runat="server" Text="label"></asp:Label>
<br />
<br />
<!--repeater starts here-->
<asp:Repeater ID="repeaterDynamic" runat="server" DataSourceID="repeaterDataSource">
<ItemTemplate>
<%#Eval("firstname")%>, <%#Eval("firstname")%>
<!--button-->
<asp:Button ID="btnRepeat" OnClick="btnRepeat_Clicked" runat="server" Text="Go" CustomerID=<%#Eval("customerID")%> />
</ItemTemplate>
<SeparatorTemplate>
<hr />
</SeparatorTemplate>
</asp:Repeater>
<!--data source-->
<asp:SqlDataSource ID="repeaterDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:myConnectionString %>"
SelectCommand="SELECT [firstname], [lastname], [customerID] FROM [customer]"></asp:SqlDataSource>
</form>
Code-behind
Protected Sub btnRepeat_Clicked(ByVal sender As Object, ByVal e As EventArgs)
'declare button
Dim btnRepeat As Button = CType(sender, Button)
'write customerID to the label
lblDisplay.Text = btnRepeat.Attributes("customerID").ToString
End Sub
|