Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Asp.net calendar control - Part 32

Suggested Videos
Part 29 - List controls in asp.net
Part 30 - Fileupload control in asp.net
Part 31 - Adrotator control in asp.net

In this video we will learn about the asp.net calendar control. Any time you want your users of the application, to provide a date, it is better to provide a calendar control from which they can select the date. In this session we will see how to do it.



Drag and drop a TextBox, ImageButton and a Calendar control on the webform. Create an Image folder and add the following Calendar.png to the Images folder.


Set the ImageUrl property of the image button to Calendar.png
ImageUrl="~/Images/Calendar.png"

HTML of the ASPX page
<asp:TextBox ID="TextBox1" runat="server" Width="115px"></asp:TextBox>
<asp:ImageButton ID="ImageButton1" runat="server" 
    ImageUrl="~/Images/Calendar.png" onclick="ImageButton1_Click" />
<asp:Calendar ID="Calendar1" runat="server" ondayrender="Calendar1_DayRender" 
    onselectionchanged="Calendar1_SelectionChanged"></asp:Calendar>



Code-Behind page code
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Calendar1.Visible = false;
    }
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
    if (Calendar1.Visible)
    {
        Calendar1.Visible = false;
    }
    else
    {
        Calendar1.Visible = true;
    }
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
    TextBox1.Text = Calendar1.SelectedDate.ToShortDateString();
    Calendar1.Visible = false;
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
    if (e.Day.IsWeekend || e.Day.IsOtherMonth)
    {
        e.Day.IsSelectable = false;
        e.Cell.BackColor = System.Drawing.Color.LightGray;
    }
}

Date Conversion methods
Response.Write("ToString() - " + DateTime.Now.ToString() + "<br/>");
Response.Write("ToLongDateString() - " + DateTime.Now.ToLongDateString() + "<br/>");
Response.Write("ToShortDateString() - " + DateTime.Now.ToShortDateString() + "<br/>");
Response.Write("ToLongTimeString() - " + DateTime.Now.ToLongTimeString() + "<br/>");
Response.Write("ToShortTimeString() - " + DateTime.Now.ToShortTimeString() + "<br/>");

Output:


DateTime format strings
Response.Write("d - " + DateTime.Now.ToString("d") + "<br/>");
Response.Write("D - " + DateTime.Now.ToString("D") + "<br/>");
Response.Write("dd/MM/yyyy - " + DateTime.Now.ToString("dd/MM/yyyy") + "<br/>");
Response.Write("dd/MMMM/yyyy - " + DateTime.Now.ToString("dd/MMMM/yyyy") + "<br/>");
Response.Write("dd/MMMM/yy - " + DateTime.Now.ToString("dd/MMMM/yy") + "<br/>");
Response.Write("MM/dd/yy - " + DateTime.Now.ToString("MM/dd/yy") + "<br/>");

Output


1 comment:

  1. Such a detailed article about calendar control.
    Thanks

    ReplyDelete

It would be great if you can help share these free resources