This
section will help us building a simple DatePicker control using Calendar
control and Javascript. Create two aspx pages, ParentPage.aspx and
Calendar.aspx. Calendar.aspx will contain a Calendar control and it
should be opened as a popup window. When the user selects a date in the
Calendar popup it will populate the date selected into a textbox in the
ParentPage.aspx page.
ParentPage.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ParentPage.aspx.cs" Inherits="ParentPage" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> <script type="text/javascript"> function PopupPicker(ctl) { var PopupWindow=null; PopupWindow=window.open('Calender.aspx?ctl='+ctl,'','width=250,height=250'); PopupWindow.focus(); } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="txtDate" runat="server"></asp:TextBox> <input id="Button2" type="button" value="Click"
onclick="PopupPicker('txtDate');" /> </div> </form> </body> </html>
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Calender.aspx.cs" Inherits="Calender" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> <script type="text/javascript"> function SetDate(dateValue,ctl) { thisForm = window.opener.document.forms[0].elements[ctl].value= dateValue; self.close(); } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:Calendar ID="Cal1" runat="Server" OnDayRender="Cal1_DayRender">
</asp:Calendar> </div> </form> </body> </html>
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Calender : System.Web.UI.Page { string ctrl; protected void Page_Load(object sender, EventArgs e) { ctrl = Request.QueryString["ctl"].ToString(); } protected void Cal1_DayRender(object sender, DayRenderEventArgs e) { HyperLink hpl = new HyperLink(); hpl.Text = ((LiteralControl)e.Cell.Controls[0]).Text; hpl.NavigateUrl = "javascript:SetDate('" + e.Day.Date.ToShortDateString()
+ "','" + ctrl + "');"; e.Cell.Controls.Clear(); e.Cell.Controls.Add(hpl); } }By default, the days in calendar control is rendered as links and generate a postback when it is clicked. Instead of postback, we will call our custom SetDate() JavaScript function by changing the cell of the Calendar control to Hyperlink control and attaching the SetDate() JavaScript function to the hyperlink in clnDatePicker_DayRender event.
No comments :
Post a Comment