February 27, 2012

Multiple Selection in ASP.NET calendar control

Below is the sample code to choose and display multiple dates selected from the calendar

CalMulitpleSelection.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CalMulitpleSelection.aspx.cs" Inherits="CalMulitpleSelection" %>


<!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></title>


</head>
<body>
  <form id="Form2" runat="server">
        <h3>Using Calendar</h3>
        Please enter your requested vacation dates:
        <asp:Calendar id="Calendar1" runat="server"   selectionmode="DayWeekMonth" 
            onselectionchanged="Cal_SelectionChanged" 
            ondayrender="Calendar1_DayRender" />
        <asp:Button ID="Show" runat="server" Text="Button" onclick="Show_Click" />
        <br>
        <asp:label id="VacationLabel" runat="Server" />
    </form>
<body>


  


</html>

CalMulitpleSelection.aspx.cs


using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;


public partial class CalMulitpleSelection : System.Web.UI.Page
{
    public static List<string> list = new List<string>();
    protected void Page_Load(object sender, EventArgs e)
    {


    }
    protected void Cal_SelectionChanged(object sender, EventArgs e)
    {
        if (Session["SelectedDates"] != null)
        {
            List<string> selectedList = (List<string>)Session["SelectedDates"];
        foreach (string s in selectedList)
        {
            Calendar1.SelectedDates.Add(Convert.ToDateTime (s));
        }
        list.Clear();
    }
    }
    protected void Show_Click(object sender, EventArgs e)
    {
        if (Session["SelectedDates"] != null)
        {
            List<string> newList = (List<string>)Session["SelectedDates"];
            foreach (string s in newList)
            {
                Response.Write(s+ "<BR/>");
            }
        }
    }


    protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
    {
        if (e.Day.IsSelected == true)
        {
            list.Add(e.Day.Date.ToString ("MM/dd/yyyy"));
        }
        Session["SelectedDates"] = list;
    }
}

No comments:

Post a Comment