HaresH Chaudhari

Freelance Web Developer

Get First and Last Date from Calender control in Asp.Net

Hello guys

Here I am going to explain how we can get the first date and last date for selected month and year from asp.net calender control. Here we just need quite easy logic on 2 events on calender. The events are Prerender and Dayrender. In PreRender, I have take session as null so everytime when page is loading, it get null before processing on calender days. Then I have write some logic to show FirstDate, Lastdate and also same for each week in the month.

C# Code
protected void Calendar1_PreRender(object sender, EventArgs e)
{
Session["FirstDay"] = null;
Session["LastDay"] = null;
}

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
if (Session["FirstDay"] == null)
Session["FirstDay"] = e.Day.Date;

if (Session["LastDay"] == null)
Session["LastDay"] = e.Day.Date.AddDays(41);

string LastDates = Convert.ToDateTime(Session["LastDay"]).ToShortDateString();
if (e.Day.Date.ToShortDateString() == LastDates)
{
DateTime FirstDate = Convert.ToDateTime(Session["FirstDay"]);
DateTime LastDate = Convert.ToDateTime(Session["LastDay"]);
Response.Write(“FirstDay:”+Session["FirstDay"].ToString() + “<br />”);
Response.Write(“LastDay:”+Session["LastDay"].ToString() + “<br />”);
for (DateTime i = FirstDate; i <= LastDate; )
{
DateTime WeekStart = i;
DateTime WeekEnd = i.AddDays(6);
Response.Write(“Week Start: ” + WeekStart.ToShortDateString() + “<br />”);
Response.Write(“WeekEnd: ” + WeekEnd.ToShortDateString() + “<br /><br />”);
i = i.AddDays(7);
}
}
}

I have also attached screen for better understand. I hope this will be helpful for you guys.

Thanks

Filed under: Asp.Net, C#.Net, Web Development, , ,

Blog Stats

  • 1,762 hits

 

April 2010
M T W T F S S
« Feb    
 1234
567891011
12131415161718
19202122232425
2627282930  
Follow

Get every new post delivered to your Inbox.