In this article I’ll explain how to use the jQuery DateTimePicker plugin in the ASP.Net GridView control.
GridView Markup
To start with I have a simple GridView with 2 columns where the first column is the name of the person and the second column is a TemplateField with ReadOnly TextBox to enter select the Date and time of birth of the person.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Person" />
<asp:TemplateField HeaderText="Date Of Birth">
<ItemTemplate>
<asp:TextBox ID="txtDOB" runat="server" ReadOnly="true" class = "Calender" />
<img src="calender.png" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
You will notice I have made the TextBox that accepts the date and time of birth ReadOnly. I have done so to prevent the users from typing the text in the TextBox. I have also added class = "Calender" attribute to the TextBox so that I can select the TextBox for dates using jQuery Selector
Finally there’s a button to Save the Records to the database. Later in the article I’ll describe how to fetch the dates from the GridView server side
Applying the DateTimePicker jQuery Plugin
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.dynDateTime.min.js" type="text/javascript"></script>
<script src="Scripts/calendar-en.min.js" type="text/javascript"></script>
<link href="Styles/calendar-blue.css" rel="stylesheet" type="text/css" />
<script type = "text/javascript">
$(document).ready(function () {
$(".Calender").dynDateTime({
showsTime: true,
ifFormat: "%Y/%m/%d %H:%M",
daFormat: "%l;%M %p, %e %m, %Y",
align: "BR",
electric: false,
singleClick: false,
displayArea: ".siblings('.dtcDisplayArea')",
button: ".next()"
});
});
</script>
You need to place the above script either on the page or the MasterPage where you want apply the DateTimePicker plugin. This DateTimePicker will automatically be applied to all TextBoxes who have attribute class = "Calender"
Screenshot
That’s all you need to do to apply the DateTimePicker jQuery plugin in ASP.Net GridView control.
Fetching the Dates Server Side
Below is how you can fetch the dates that the user has submitted by looping through the rows of the GridView Control
C#
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
DateTime dob = DateTime.Parse(Request.Form[row.FindControl("txtDOB").UniqueID]);
//Save the date to Database here
}
}
VB.Net
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs)
For Each row As GridViewRow In GridView1.Rows
Dim dob As DateTime = DateTime.Parse(Request.Form(row.FindControl("txtDOB").UniqueID))
'Save the date to Database here
Next
End Sub
Downloads
That’s it in this article. You can download the complete source code in C# and VB.Net using the download link below
Download Code