Creating an Event Calendar
By AzamSharp
Views: 17399

Introduction:

 

Our life is filled with events, lots of events. To accomplish most if not all we must schedule them on certain dates. This task is accomplished by marking the important dates on the calendar. In this article I will demonstrate how to create a very simple Event Calendar using ASP.NET.

 

Database Design:

 

The database consists of a single table called “Schedules”. The schedules table contains the following fields:

 

ScheduleID: This is the primary key of the table.

 

Title: This holds the title of the task.

 

ScheduleDate: The scheduled date of the task.

 

The purpose of the table is to hold the events scheduled for the particular day.

 

Retrieving Data from the Database:

 

The next step is to retrieve the data from the database. For this I have created a small method called GetDate() which returns the DataSet.

 

private DataSet GetData()

    {

        string connectionString = "Server=localhost;Database=School;Trusted_Connection=true";

        SqlConnection myConnection = new SqlConnection(connectionString);

        SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Schedules", myConnection);

 

        DataSet ds = new DataSet();

        ad.Fill(ds);

 

        return ds;

    }

 

The next step is to populate the Calendar with the data from the database.

 

Using the DayRender Event to Populate Calendar:

 

The DayRender event of the Calendar control is fired each time the day is rendered. This is the perfect place to fill the calendar day box with the custom data.

 

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)

    {

        DataSet ds = GetData();

 

        string link = "<a href='ScheduleDetails.aspx?scheduleID=";

 

        string s = e.Day.Date.ToShortDateString();

 

        e.Cell.Text = e.Day.Date.Day.ToString() + "<BR>";

 

        LiteralControl l = new LiteralControl();

        l.Text = e.Day.Date.Day.ToString() + "<BR>";

        e.Cell.Controls.Add(l);

 

        foreach (DataRow row in ds.Tables[0].Rows)

        {

            string scheduledDate = Convert.ToDateTime(row["ScheduleDate"]).ToShortDateString();

 

            if (scheduledDate.Equals(s))

            {

                LinkButton lb = new LinkButton();

                lb.Text = link + (int)row["ScheduleID"] + "'>" + row["Title"] as String + "</a>" + "<BR>";

                e.Cell.Controls.Add(lb);              

            }         

        }

 

        HtmlAnchor anchor = new HtmlAnchor();

        anchor.InnerHtml = "Add";

       

        string method = "ShowAddTaskPane(event,'" + e.Day.Date.ToShortDateString() + "')";

 

        anchor.href="#";

        anchor.Attributes.Add("onclick", method);

        e.Cell.Controls.Add(anchor);      

     

    }

 

I know you must be wondering that why the DayRender contains all that code. Well, aside from populating the Calendar day box with the title of the event we are also making them hyperlinks so the user can view the details of that event. Also, we are adding an “Add” button which allows to quickly adding new events. Now, if you run the page you will see the Calendar filled with the events.

     

 

The above image shows what the calendar will look like when it is rendered on the page. If you hover over the event then you will notice that it is pointing to the “ScheduleDetails.aspx” page. You can easily create “ScheduleDetails.aspx” page which, simply shows the details about the event.

 

Adding a New Event:

 

Adding a new event can be accomplished in number of ways which includes sending the user to a new page which shows the fields associated with adding an event. In my opinion user should not be send to a different page and the “Add Event” feature should be available on the same page where the calendar is displayed. So, let’s see how we can allow the user to add the event(s) without leaving the calendar page.

 

The first task is to create a <DIV> element which contains a TextBox and a Button control to add a new event.

 

<div id="AddTaskPane" onblur="this.style.visibility='hidden'" style="position:absolute; visibility:hidden; width:200px; height:100px; background-color:#FFFF66">

      

       Enter Title: <asp:TextBox ID="txtTitle" runat="server" />

      

           <asp:Button ID="Btn_AddTask" runat="server" Text="Add Task" OnCommand="Btn_AddTask_Command" />     

      

      

       </div>

 

The <DIV> is made invisible and will only appear when the “Add” link is clicked. The code to create the “Add” link is inside the DayRender event but I am re-pasting it so that you will have a better idea.

 

HtmlAnchor anchor = new HtmlAnchor();

        anchor.InnerHtml = "Add";

       

        string method = "ShowAddTaskPane(event,'" + e.Day.Date.ToShortDateString() + "')";

 

        anchor.href="#";

        anchor.Attributes.Add("onclick", method);

        e.Cell.Controls.Add(anchor); 

 

 

The ShowAddTaskPane is fired when the user clicks on the “Add” link. Let’s take a look at the ShowAddTaskPane method.

 

function ShowAddTaskPane(e,selectedDate)

{

 

    var ev = e || window.event;  

   

     

    document.getElementById("AddTaskPane").style.visibility  = 'visible';

    document.getElementById("AddTaskPane").style.top = ev.clientY;

    document.getElementById("AddTaskPane").style.left = ev.clientX; 

   

    CallServer(selectedDate,''); 

    

}  

 

The ShowAddTaskPane method takes two arguments which are event e and the selectedDate.  The event e is used to display the <DIV> in the current mouse clicked position. The CallServer method calls the server side method using ASP.NET 2.0 Client Callbacks. I will talk about it later in this article.

 

The effect is shown in the image below. The <DIV> will appear on the same position the mouse is clicked.

 

 

  

How to Find the Selected Date:

 

Now, I will answer the question that why the ShowAddTaskPane contains the parameter selectedDate and what is the purpose of the CallServer method. The selectedDate is passed so, that we will know which “Add” link is clicked inside the Calendar. The CallServer method sends the selectedDate to the code behind and stores it in the Session variable. This way the selected date is maintained. You might be wondering that the ViewState should have been a better choice of storing the selected date unfortunately, the ViewState will not work and will be null every time.

 

The code to initialize the client callbacks and inserting the new event in the database is available in the download.

 

Conclusion:

 

In this article we learned how to create a simple event calendar. The calendar can be extended to include deleting and editing an event. I leave this exercise for the reader.

 

I hope you liked this article, happy coding!



UPDATE(02/06/2007): The download sample has been updated. The code now works with IE and FireFox.

 

[Download Sample]




 

By AzamSharp


Enter Comment/Feedback
  •  
  •  
  •  
  •  
  •  

Comments/Feedbacks
Subject: FireFox
Name: FABIO MANS
Date: 2/6/2007 10:41:11 AM
Comment:
Very good, but in Firefox don´t open the div.

[]s


Fabio Mans
Subject: FireFox Code
Name: AzamSharp
Date: 2/6/2007 12:43:09 PM
Comment:
Hi Fabio,

You can include this code to work with FireFox. Simply, add this code in the ShowAddTaskPane method:

var ev = e || window.event;


document.getElementById("AddTaskPane").style.visibility = 'visible';


// if the browser is IE
if(navigator.appName == 'Microsoft Internet Explorer')
{
document.getElementById("AddTaskPane").style.top = ev.clientY;
document.getElementById("AddTaskPane").style.left = ev.clientX;
}

// if the browser is FIREFOX
else if(navigator.appName == 'Netscape')
{

document.getElementById("AddTaskPane").style.top = ev.clientY + 'px';
document.getElementById("AddTaskPane").style.left = ev.clientX + 'px';
}

CallServer(selectedDate,'');
Subject: Animation!
Name: AzamSharp
Date: 2/6/2007 1:07:20 PM
Comment:
For those who are interested in viewing the animation of the Event Calendar please check out the following post:

http://aspadvice.com/blogs/azamsharp/archive/2007/02/06/Creating-a-Simple-Event-Calendar.aspx
Subject: asp.net
Name: Mario
Date: 3/21/2007 7:29:20 PM
Comment:
hello,

I like your calendar - It's just what I was looking for.

I am just starting out with asp.net using Visual studio 2005 and was hopping you can give me some direction on how to learn to code in asp.net.

Thanks in advance...
Subject: Callback Vs. Hidden Field
Name: Loren Van Spronsen
Date: 3/25/2007 8:34:52 AM
Comment:
Very good article, but I would prefer to sub out the AJAX callback that stores the date in a Session variable for a hidden field.

Enter Title:






protected void Page_Load(object s, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(typeof(Page), "AddEventDateHiddenFieldDeclaration", "var dateHF = document.getElementById('" + hfDate.ClientID + "');", true);
}


if you swap in the above code, than you can simply modify dateHF.value in your ShowAddTaskPanel function instead of performing the server callback. And now you can access the selected date as hfDate.Value on the server...
Subject: How Many Database hits?????
Name: David
Date: 3/25/2007 10:13:59 AM
Comment:
42?????

Isnt it going to hit the db 42 different times?

Wouldn't it be better to put the GetData() in the MonthChange event?

Then in the day render filter the table based on current day?
Subject: Callback Vs. Hidden Field
Name: Loren Van Spronsen
Date: 3/25/2007 10:34:27 AM
Comment:
Something went wonky with that last entry, I guess you can't enter .NET control markup into these feedback forms... Anyways, you would have to add a .NET Hidden Field control with an id of hfDate to the page...
Subject: The school database script
Name: daniel
Date: 3/26/2007 6:40:46 PM
Comment:
Dear, excellent article. Please would you guide us to where is the School sql script. Thanks.
Subject: Convert to VB
Name: mhlove
Date: 4/6/2007 11:03:44 AM
Comment:
I am working with ASP.NET VS-2005 using VB as code behind. Can you help by converting the C to VB? i tried, but could not get it right.
Subject: Nice One
Name: anwar
Date: 4/17/2007 2:51:58 AM
Comment:
Thanx a lot
Subject: Getting the hourly events
Name: shanth kumar N
Date: 5/14/2007 1:12:24 PM
Comment:
Hi

the code u have given is really awesome, but the problem is i gives the day schedule,
i want the hourly schedule for the particular day. so please do send me some idea or the code snippets to me.

and thanks to the code u have given
Subject: to know "add" link in other page
Name: shanth kumar N
Date: 5/15/2007 7:47:30 AM
Comment:
please tell me how The selectedDate is passed to other page so, that we will know which “Add” link is clicked inside the Calendar.
Subject: ASP.NET
Name: Venkata
Date: 6/21/2007 1:20:45 AM
Comment:
hello,

I like your calendar - It's just what I was looking for in this articals

I am just starting out with asp.net using Visual studio 2005 and was hopping you can give me some direction on how to learn to code in asp.net...and c#

Thanks&Regards,
Venkata
Subject: asp.net
Name: cosmo_vk
Date: 7/4/2007 11:56:22 PM
Comment:
Hi!
I long searched for an example of a code that the calendar took data from base. It is a fine example.
Thanks for it!

Alex, Russia


Subject: Thanx Azam Sharp
Name: meharaj
Date: 8/1/2007 11:08:19 PM
Comment:
Hi,
Thanx, It's just what I was looking for.But any one can help the same code in vb.net

Thanx,

Warm Regards,
Meharaj
Subject: some more great visible caldayrender
Name: naveen
Date: 11/17/2007 1:30:47 AM
Comment:
this is great article:-
some more great look i am sending extra code here:-
protected void caldayrender(object sender, DayRenderEventArgs e)
{
Style eventstyle = new Style();
eventstyle.BackColor = Color.AntiqueWhite;
eventstyle.BorderColor = Color.White;
eventstyle.BorderWidth = 2;
ds2 = bindxml();
string s = e.Day.Date.ToShortDateString();
foreach (DataRow row in ds2.Tables[0].Rows)
{

string scheduledDate = Convert.ToDateTime(row["your preority column name thats must and should be date formatable"]).ToShortDateString();
if (( s == scheduledDate)&&(!e.Day.IsOtherMonth))
{
e.Cell.ApplyStyle(eventstyle);
String url = e.SelectUrl;
e.Cell.Controls.Clear();
HyperLink link = new HyperLink();
link.Text = Convert.ToString(e.Day.Date.Day);
link.ToolTip = "This is Event";
link.NavigateUrl = url;
e.Cell.Controls.Add(link);
}
else
{
e.Day.IsSelectable = false;
}
}
Subject: Event Calendar
Name: Donal
Date: 2/24/2008 9:06:02 AM
Comment:
This seemed just what i was looking for, unfortunately clicking the "Download Sample" link leads to a page not found and my knowledge isnt sufficient to make it from your tutorial.
Subject: RE: Event Calendar
Name: AzamSharp
Date: 2/24/2008 11:43:29 AM
Comment:
Hi Donal, You can check out the following link and download from there. http://www.gridviewguy.com/ArticleDetails.aspx?articleID=232_Creating_an_Event_Calendar
Subject: Article
Name: Jenny
Date: 6/9/2008 11:23:54 PM
Comment:
Great article - thanks very much.



Join WebHost4Life.com