In the last day at my work I had a situation where I have to get all the textbox which are for date of birth entry inside a repeater control and set a jQuery calendar with it. You may be having many simple solutions for this problem, but I have a tricky one today.
To demonstrate this I am using a simple example. Suppose I have to show first ten company names from Customers table in Northwind database. Here I am using Entity Framework for that. So my code will be following.
public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { using (NorthwindEntities entities = new NorthwindEntities()) { rptCustomer.DataSource = entities.Customers.OrderBy(name => name.CompanyName).Take(10); rptCustomer.DataBind(); } } }
Now I have a repeater to show company names.
<asp:Repeater ID="rptCustomer" runat="server"> <HeaderTemplate> <h2>Company Name</h2> <ul> </HeaderTemplate> <ItemTemplate> <li> <asp:HyperLink ID="lblCompanyName" runat="server" Text='<%# Eval("CompanyName") %>' NavigateUrl="#" /> </li> </ItemTemplate> <FooterTemplate> </ul> </FooterTemplate> </asp:Repeater>
Now it will show first ten company names. Now suppose I want functionality in which when user click on any company name link an alert will be shown. How I took the link element which is generated by the at runtime? It is inside a repeater. Now the tricky solution. Before that I should tell you that I was stuck in this situation, the solution was from one of my co-worker.
I am creating a blank css class at the top of the page.
<style type="text/css"> .dummy { } </style>
Now I am set this css class with the inside the repeater.
<asp:HyperLink ID="lblCompanyName" runat="server" Text='<%# Eval("CompanyName") %>' NavigateUrl="#" CssClass="dummy" />
Now I am using jQuery.
<script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('.dummy').click(function () { alert('Thank you'); }); }); </script>
It will find all the element with the dummy css class and show the alert when it has been clicked. I know that only the company names links have that css class. So it will apply on them only.
Nice and easy. Please share if you have any better solution or idea on this.