In this article I will explain with an example, how to implement the
jQuery DatePicker (Calendar) with TextBox in ASP.Net using C# and VB.Net.
This article will also illustrate how to get the selected Date of the
jQuery DatePicker (Calendar) on Server Side (Code Behind) on Button click in ASP.Net using C# and VB.Net.
HTML Markup
The following HTML Markup consists of:
TextBox – For implementing
jQuery DatePicker.
The ReadOnly property of the TextBox is set to TRUE.
Button – For displaying selected date.
The Button has been assigned with an OnClick event handler.
<asp:TextBox ID="txtDate" runat="server" ReadOnly="true"></asp:TextBox>
<hr />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="OnSubmit" />
Applying jQuery UI DatePicker Plugin to ASP.Net TextBox
Inside the HTML, the following
jQuery UI CSS script file is inherited.
1. jquery-ui.css
And then, the following
jQuery and
jQuery UI JS files are inherited.
1. jquery.min.js
2. jquery-ui.js
Inside the
jQuery document ready event handler, the TextBox has been applied with the
jQuery DatePicker plugin.
The
jQuery DatePicker plugin has been assigned with the following properties:
showOn – button
For showing
jQuery DatePicker only when the Button next to the TextBox is clicked.
buttonImageOnly – true
This indicates that the Image will be a Button.
buttonImage – URL
The path of the Image file to be displayed as Button.
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=txtDate]").datepicker({
showOn: 'button',
buttonImageOnly: true,
buttonImage: 'images/calendar.png'
});
});
</script>
Fetching the value of the Selected Date on Server Side
When the Submit Button is clicked, the value of the Selected Date is fetched from the Request.Form collection.
Finally, the selected Date is displayed using JavaScript Alert Message Box using the RegisterStartupScript method.
Note: Request.Form collection is used as in some browsers the Text property does not hold the value set from Client Side when the TextBox is set as ReadOnly.
C#
protected void OnSubmit(object sender, EventArgs e)
{
string dt = Request.Form[txtDate.UniqueID];
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Selected Date: " + dt + "');", true);
}
VB.Net
Protected Sub OnSubmit(sender As Object, e As System.EventArgs)
Dim dt As String = Request.Form(txtDate.UniqueID)
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Selected Date: " & dt & "');", True)
End Sub
Screenshot
Demo
Downloads