Click here to Skip to main content
Email Password   helpLost your password?

New_CAL.JPG

Introduction

This is a calendar part which displays events from an existing event list (dates highlighted), and also provides details about an event on the click of the event date.

Background

To create this WebPart, I chose the ASP.NET Calendar control and has overridden its OndayRender method to give colors to the dates with events.

The SharePoint object model (Microsoft.sharepoint.dll) is then used to pull the event details, displayed on the click of the date.

There are two classes used:

  1. A class to highlight the event dates and to give colors to the dates of the calendar (e.g., gray for weekends).
  2. A WebPart to create and render the Calender control and to display the event details pulled from the event list, on click of the highlighted date.

Using the code

Steps to create the Calendar class:

  1. Create a C# class library project in ASP.NET.
  2. Name it as WebPart_Calendar.
  3. Name the class CustomCalendar.
  4. Add these libraries to the project:

Use the following code to give colors for weekend dates, dates of other months, and dates with events. In the code below, events are pulled from an event list named Team Calendar (you can change the list name if you wan to).

namespace WebPart_Calendar
{
    public class CustomCalendar : System.Web.UI.WebControls.Calendar
    {
        protected override void OnDayRender(TableCell cell, CalendarDay day)
        {
            if (day.IsToday)
            {
                cell.Attributes.Add("style", 
                  "font-weight:bold;background:#cee7ff;");
            }
            else if (day.IsWeekend)
            {
                cell.BackColor = System.Drawing.Color.LightGray;
            }
            else if (day.IsOtherMonth)
            {
                cell.BackColor = System.Drawing.Color.LightGray;
            }
            else
            {
                SPSite siteCollection = SPContext.Current.Site;
                SPList calendarList = 
                  siteCollection.RootWeb.Lists["Team Calendar"];
                // Construct a query that expands recurring events
                SPQuery query = new SPQuery();
                query.ExpandRecurrence = true;
                query.CalendarDate = day.Date;
                query.Query = "EventDate FieldName<where>" + 
                      "<eq><fieldref name="""\""">" + 
                      "<value type="""\""">" + 
                      day.Date.ToString("yyyy-MM-ddTHH\\:mm\\:ssZ") + 
                      "</value></eq></where>";

                // Returns all items that would appear
                // in the calendar view for the current day
                SPListItemCollection calendarItems = 
                                     calendarList.GetItems(query);

                if(calendarItems.Count > 0){
                    cell.BackColor = System.Drawing.Color.Khaki;
                    cell.Attributes.Add("style", "font-weight:bold;");
                }
            }
        }
    }

Build the project to get WebPart_Calendar.dll.

Steps to create a Webpart class:

  1. Create a Webpart Template Project (New -> Project-> C#-> SharePoint -> WebPart).
  2. Name it SPWebPart_Calendar.
  3. Add a reference to these libraries:

The code goes below:

namespace SPWebPart_Calendar 
{ 
    [Guid("7cd9a020-6a9d-4765-8138-ed85d648e553")] 
    public class WebPart_Calendar_Class : 
           System.Web.UI.WebControls.WebParts.WebPart 
    { 
        CustomCalendar cal; 
        Label lbl; 

        public WebPart_Calendar_Class() 
        { 
            this.ExportMode = WebPartExportMode.All; 
        } 

        protected override void Render(HtmlTextWriter writer) 
        { 
            EnsureChildControls(); 
            cal.RenderControl(writer); 
            lbl.RenderControl(writer); 
        } 

        protected override void CreateChildControls() 
        { 
            cal = new CustomCalendar(); 
            this.cal.ID = "Calendar1"; 
            this.cal.CellPadding = 5; 
            this.cal.CellSpacing = 2; 
            this.cal.BorderColor = System.Drawing.Color.LightGray; 
            this.cal.TitleStyle.BackColor = 
              System.Drawing.ColorTranslator.FromHtml("#f2f2f2"); 
            this.cal.TitleStyle.ForeColor = 
              System.Drawing.ColorTranslator.FromHtml("#6c6b6b"); 
            this.cal.DayHeaderStyle.ForeColor = 
              System.Drawing.ColorTranslator.FromHtml("#818080"); 
            this.cal.DayStyle.ForeColor = 
              System.Drawing.ColorTranslator.FromHtml("#9f9e9e"); 
            this.cal.OtherMonthDayStyle.ForeColor = 
              System.Drawing.ColorTranslator.FromHtml("#CCCCCC"); 
            this.cal.OtherMonthDayStyle.BackColor = 
              System.Drawing.ColorTranslator.FromHtml("#f2f2f2"); 
            this.Controls.Add(cal); 
            lbl = new Label(); 
            this.lbl.ID = "Label1"; 

            this.lbl.Visible = false; 
            this.lbl.EnableViewState = false; 
            this.Controls.Add(lbl); 
            this.cal.SelectionChanged += new EventHandler(cal_SelectionChanged); 
        } 

        protected void cal_SelectionChanged(object sender, EventArgs e) 
        { 
            //this.lbl.Text = this.cal.SelectedDate.Date.ToShortDateString(); 
            SPSecurity.CodeToRunElevated listEvents = 
              new SPSecurity.CodeToRunElevated(delegate() 
              { RenderEventsByDate(this.cal.SelectedDate); }); 
            SPSecurity.RunWithElevatedPrivileges(listEvents); 
            //RenderEventsByDate(this.cal.SelectedDate); 
            this.lbl.Visible = true; 
        } 

        public void RenderEventsByDate(DateTime selectedDate) 
        { 
            //Get the calendar events for that day 
            SPSite siteCollection = SPContext.Current.Site; 

            SPList calendarList = 
              siteCollection.RootWeb.Lists["Team Calendar"]; 

            // Construct a query that expands recurring events 
            SPQuery query = new SPQuery(); 
            query.ExpandRecurrence = true; 
            query.CalendarDate = selectedDate; 
            query.Query = "EventDate FieldName <where />" + 
               "<eq><fieldref name="""\""" />" + 
               "<value type="""\""" />" + 
               selectedDate.ToString("yyyy-MM-ddTHH\\:mm\\:ssZ") + 
               "</value></eq></where>"; 
            query.ViewFields = " Fields to View fromEvent List";
            SPListItemCollection calendarItems = calendarList.GetItems(query); 

            foreach (SPListItem item in calendarItems) 
            { 
                this.lbl.Text += item["Title"] + ": starts " + 
                     item["EventDate"].ToString() + " and ends " + 
                     item["EndDate"].ToString() + ""; 
            } 
            //If there are no events, display the message 
            if (String.IsNullOrEmpty(this.lbl.Text)) 
                this.lbl.Text = " There are no events for this date "; 
        } 
    } 
}

Finally, deploy the WebPart as a solution. Here is how to deploy this as a solution package: http://programmingsharepoint.blogspot.com/2008/03/deploy-webpart-as-solution-package.html. For more details, see: http://programmingsharepoint.blogspot.com/.

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralMy vote of 1 [modified]
lwp850210
18:43 29 Oct '09  
:( poor

try this:

query.Query = "<Where>" +
"<Eq><FieldRef Name=\"EventDate\" />" +
"<Value Type=\"DateTime\" >" +
day.Date.ToString("yyyy-MM-ddTHH\\:mm\\:ssZ") +
"</Value></Eq></Where>";
GeneralRe: My vote of 1
silverstars
21:15 31 Oct '09  
yes it worked !

Thank you veryyyyyyyy much lwp850210 !

Smile
GeneralErrors :(
silverstars
3:27 29 Oct '09  
hi Isha ,

I hope you see this soonFrown

Well I am having problems with the calendar webpart :
1- there is an error in the ventDate FieldName""\""" />""\""" />"

and I tried to solve it with ventDate FieldName'\'/>'\'/>"

2-May I ask you to send the project ? since I am trying to deploy it ,but it doesnt want to add the webpart saying troublshoot webpart and error to the deployed solutionFrown


Thank you in advance Smile
GeneralUnexpected Charactor
krishna369
19:36 28 Oct '09  
can you please help me with this \ unexpected error and ; expected error

in the code " +
"" +
selectedDate.ToString("yyyy-MM-ddTHH\\:mm\\:ssZ") +


error says
Error 1 Unexpected character '\'
Error 2 ;expected
GeneralAgregar un Calendar y asociar los eventos a una lista de SP
edudebolivar
7:00 22 Oct '08  
La idea es poder hacer todo esto programáticamente desde un WP.
Espero sus comentarios.
Saludos cordiales,
GeneralOne Question About Calendar Types.
hdv212
7:11 9 Oct '08  
Hi Kapoorisha

Thanks for your article, i have question about calendar types, my problem is that i want to add a new calendar type to Site Collection > Regional Setting > Calendar Type drop down list,but i don't know how to do this, i don't want to create a webPart, i want to add new calendar type to Calendar Type list in Regional Settings, can u help me ?
thanks
Generalcode not built due to error...
Kuldeep Kadyan
3:22 6 May '08  
Hi,

Basically i am new to development, so when i try to implement this solution. I hanged up with some error on this line:-

query.Query = "EventDate FieldName""\""" />""\""" />;" + day.Date.ToString("yyyy-MM-ddTHH\\:mm\\:ssZ") + "";


Because of this the code is not going to built.

Can you suggest me what i have to do???

Thanks
Kuldeep Kadyan
General[Message Deleted]
subanboy
6:29 7 May '08  

GeneralRe: code not built due to error...
Kuldeep Kadyan
20:27 7 May '08  
Hi,

I am confused here what i have to put here. What your are doing here in this query.

"EventDate FieldName""\""" />""\""" />"

Can you explain it to me how it is returning the recurring events???

Thanks
Kuldeep Kadyan
GeneralRe: code not built due to error...
edudebolivar
6:59 22 Oct '08  
Hi!
Aparentemente nadie contesta.
Si conocen algún sitio en donde podamos evacuar las dudas, no duden en agregarlos como link en un mensaje.
Que tengan buen día.
Saludos cordiales,

Javier Ramos
GeneralRe: code not built due to error...
krishna369
19:38 28 Oct '09  
please write in english
GeneralRe: code not built due to error...
edudebolivar
10:52 31 Oct '09  
Sorry, but my english is bad.
I working into WSS 3.0 development web parts in c#. I have any error into render control for the javascript code. I searching links to help me with the problems and i not found. My problem is finish now with MOSS 2007. Thank you anyway. Regards.


Last Updated 27 Apr 2008 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010