Follow by Email

Wednesday, 22 August 2012

Date Picker in Asp.Net

Date Picker in Asp.Net


First you need to add a calendar control to your page. Put the following code somewhere in your BODY section
<div id="dateField" style="display:none;">
<asp:Calendar id="calDate"
OnSelectionChanged="calDate_SelectionChanged"
Runat="server" />
</div>
Notice the OnSelectionChanged event. This is calling a method we will display later to handle the clicking of a date in the calendar.
We also need a textbox to put the resulting date, and also a link to open the calendar. The cal.png is just a calendar icon you can use whatever you like for the image.
<asp:TextBox
id="txtDate"
Runat="server" />
<img src="cal.png" onclick="popupCalendar()" />
You’ll notice the onclick event on the  tag. You need to create some javascript to open the popup window. Put the following in your HEAD section.
<script type="text/javascript">
function popupCalendar()
{
var dateField = document.getElementById('dateField');

// toggle the div
if (dateField.style.display == 'none')
dateField.style.display = 'block';
else
dateField.style.display = 'none';
}
</script>
This code established where the DIV block is and set it to visable (block).
Now we need to add the code to process all of this. Either put this code in your code behind or within <script runat=”server”> tag at the top of the page.
C#
protected void calDate_SelectionChanged(object sender, EventArgs e)
{
txtDate.Text = calDate.SelectedDate.ToString("d");
}

0 comments:

Post a Comment


                                                            

 
Design by Abhinav Ranjan Sinha