ARTICLE

Event Calender in ASP.Net

Posted by Krishna Garad Articles | ASP.NET Programming January 11, 2011
This article explains how you can manage an event calender in ASP.Net.
Reader Level:
Download Files:
 

Introduction:

This article explains how you can manage an event calender in ASP.Net. The event calender can store event details in a database. Many people need to manage events on a website; organizations such as a college that have to manage it's event's, holydays etc.. They can manage their events with this event calender.

This calender is based on the "Data Driven Event Calender" article by Munir Sheikh on this website. I have just added some User Friendly functionality to existing article by some JavaScript. Let's take a look at Event Calender.

In this article I used some third party calender dll file. With some events where I can enter in binding the data to calender control.

Using Coding:

In calender control if we want to add the content we have an event with id "DayRender" Event. In which we can enter into the calender and can add our controls and can bind the data to our controls. For preparing events I have done the same thing here. I used this "DayRender" Event of calender control and added some control to calender to show an event for a specific date.

Before entering into the "Dayrender" we have to prepare our event source. For this you can get the data from database and can add the event to database also. In the code for the event source I have used both methods. With Source code you can see the appropriate things I have commented for understanding. For this purpose I have created a Dataset on the fly with some data as below. Take a look at Page_Load event.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataSet GetEve = GetEvents();
            calender.EventStartDateColumnName = "EventDate";
            calender.EventEndDateColumnName = "EventDate";
            calender.EventDescriptionColumnName = "EventDesc";
            calender.EventHeaderColumnName = "EventDesc";
            calender.EventBackColorName = "BackColor";
            calender.EventForeColorName = "ForeColor";
            calender.EventSource = GetEve.Tables[0];
            string sbReference = ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
            string cbScript = String.Empty;
            // check if the script is already registered or not
            if (!ClientScript.IsClientScriptBlockRegistered("CallServer"))
            {
                cbScript = @" function CallServer(arg,context) { " + sbReference + "}";
                ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", cbScript, true);
            }
        }
    }
    // Create DataBase Table Or Create Your Own Dataset containing Values
    private DataSet GetEvents()
    {
        DataSet ds = new DataSet();
        DataTable dt = new DataTable("Tbl_EventDetails");
        DataColumn dc = new DataColumn("SrNo", typeof(int));
        DataColumn dc1 = new DataColumn("EventDesc", typeof(string));
        DataColumn dc2 = new DataColumn("EventDate", typeof(DateTime));
        DataColumn dc3 = new DataColumn("BackColor", typeof(string)); 
        DataColumn dc4 = new DataColumn("ForeColor", typeof(string));
        dt.Columns.Add(dc);
        dt.Columns.Add(dc1);
        dt.Columns.Add(dc2);
        dt.Columns.Add(dc3);
        dt.Columns.Add(dc4);
        DataRow dr;
        dr = dt.NewRow();
        dr["Srno"] = "1";
        dr["EventDesc"] = "First Day";
        dr["EventDate"] = DateTime.Now.ToShortDateString();
        dr["BackColor"] = "White";
        dr["ForeColor"] = "Red";
        DateTime _seconday = DateTime.Now.AddDays(1);
        DataRow dr1;
        dr1 = dt.NewRow();
        dr1["Srno"] = "2";
        dr1["EventDesc"] = "Second Day";
        dr1["EventDate"] = _seconday;
        dr1["BackColor"] = "White";
        dr1["ForeColor"] = "Red";
        DateTime _thirdday = DateTime.Now.AddDays(2);
        DataRow dr2;
        dr2 = dt.NewRow();
        dr2["Srno"] = "3";
        dr2["EventDesc"] = "Third Day";
        dr2["EventDate"] = _thirdday;
        dr2["BackColor"] = "White";
        dr2["ForeColor"] = "Red";
        dt.Rows.Add(dr);
        dt.Rows.Add(dr1);
        dt.Rows.Add(dr2);
        ds.Tables.Add(dt);
        return ds;      
    }

Here I had prepared only the event source for my calender. Alternatively you can get your event source from a database. Now we will see the event where I can do the "DayRender" event of the calender control.

    protected void calender_DayRender(object sender, DayRenderEventArgs e)
    {
        DataSet ds = GetEvents();
        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 calender.EventSource.Rows)
        {
            string scheduledDate = Convert.ToDateTime(row["EventDate"]).ToShortDateString();
            if (scheduledDate.Equals(s))
            {
                Label lbl = new Label();
                lbl.Text = row["EventDesc"].ToString() + "</a>" + "<BR>";
                lbl.BackColor = System.Drawing.Color.White;
                lbl.ForeColor = System.Drawing.Color.Red;
                e.Cell.Controls.Add(lbl);
            }
        }
        HtmlAnchor anchor = new HtmlAnchor();
        anchor.InnerHtml = "Add/";
        HtmlAnchor anc = new HtmlAnchor();
        anc.InnerHtml = "Remove";
        string method = "ShowAddTaskPane(event,'" + e.Day.Date.ToShortDateString() + "')";
        string method2 = "ShowRemoveTaskPane(event,'" + e.Day.Date.ToShortDateString() + "')";
        anchor.HRef = "#";
        anc.HRef = "#";
        anchor.Attributes.Add("onclick", method);
        anc.Attributes.Add("onclick", method2);
        e.Cell.Controls.Add(anchor);
        e.Cell.Controls.Add(anc);
    }

In above event you can see what I have done; just created one label control which will hold the Event Description From my EventSource. Like

                Label lbl = new Label();
                lbl.Text = row["EventDesc"].ToString() + "</a>" + "<BR>";
                lbl.BackColor = System.Drawing.Color.White;
                lbl.ForeColor = System.Drawing.Color.Red;
                e.Cell.Controls.Add(lbl);

As well I had added this label control to calender control. You can add other controls also such as the label control. I've added some anchor on each date say for adding and removing the event from the selected date anchor. This is only for getting postback and raising the event to perform event addition and removal. In page load you seen I've registered a script. With this we can perform our event addition and removal.

Actually this anchor will raise event and activate a Javascript function. In aspx page I have created some invisible panel with <div> element with contain some ASP.Net controls like textbox for event description, DropDownlist for colour selection and button to add the event details in Database. See at JavaScript

   <div id="AddTaskPane" onblur="this.style.visibility='hidden'" style="position:absolute; visibility:hidden; width:220px; height:100px; background-color:#C0C0C0; z-index:55555">
       <table>
       <tr>
       <td colspan="2" align="right">     
       <a href="#" onclick="HideTaskPane()"><asp:Image ID="imgdelete" runat="server" ImageUrl="~/close.gif" /></a>
       </td>
       </tr>
       <tr>
       <td>
       Enter Title:
       </td>
       <td>
        <asp:TextBox ID="txtTitle" runat="server" />
       </td>
       </tr>
       <tr>
       <td>
       Fore Color
       </td>
       <td colspan="2" align="center">
       <asp:DropDownList ID="forecolor" runat="server">
       <asp:ListItem>Choose Color</asp:ListItem>
       <asp:ListItem>Red</asp:ListItem>
       <asp:ListItem>Green</asp:ListItem>
       <asp:ListItem>Blue</asp:ListItem>
       <asp:ListItem>Black</asp:ListItem>
       </asp:DropDownList>
       </td>
       </tr>
       <tr>
       <td>
       Back Color
       </td>
       <td colspan="2" align="center">
       <asp:DropDownList ID="backcolore" runat="server">
       <asp:ListItem>Choose Color</asp:ListItem>
       <asp:ListItem>Red</asp:ListItem>
       <asp:ListItem>Green</asp:ListItem>
       <asp:ListItem>Blue</asp:ListItem>
       <asp:ListItem>Black</asp:ListItem>
       </asp:DropDownList>
       </td>
       </tr>
       <tr>
       <td colspan="2" align="center">
       <asp:Button ID="Btn_AddTask" runat="server" Text="Add Task" OnCommand="btnadd_Click" />
       </td>
       </tr>
       </table>
       </div>
       <div id="RemoveTask" onblur="this.style.visibility='hidden'" style="position:absolute; visibility:hidden; width:220px; height:100px; background-color:#C0C0C0; z-index:55555">
       <table>
       <tr>
       <td colspan="2" align="right">     
       <a href="#" onclick="HideRemovePane()"><asp:Image ID="imgdel" runat="server" ImageUrl="~/close.gif" /></a>
       </td>
       </tr>
       <tr>
       <td colspan="3" align="center">
       <strong style="font-size:small; color:Red; font-style:normal;">WARNING!</strong><br />
       All Events Related On<br />
       This Day Will Be Removed
       </td>
       </tr>
       <tr>
       <td colspan="2" align="right">
       <asp:Button ID="btnremove" runat="server" Text="RemoveTask" OnCommand="btnremove_Click" />
       </td>
       </tr>
       </table>     
       </div>
       <input type="hidden" id="hiddenSelectedDate" runat="server" />&nbsp;<br />
    </form>
    <script language="javascript" type="text/javascript">
        function HideTaskPane() {
            document.getElementById("AddTaskPane").style.visibility = 'hidden';
        }
        function HideRemovePane() {
            document.getElementById("RemoveTask").style.visibility = 'hidden';
        }
        function ShowAddTaskPane(e, selectedDate) {
            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, '');
        }
        function ShowRemoveTaskPane(e, selectedDate) {
            var ev = e || window.event;
            document.getElementById("RemoveTask").style.visibility = 'visible';
            // if the browser is IE
            if (navigator.appName == 'Microsoft Internet Explorer') {
                document.getElementById("RemoveTask").style.top = ev.clientY;
                document.getElementById("RemoveTask").style.left = ev.clientX;
            }
            // if the browser is FIREFOX
            else if (navigator.appName == 'Netscape') {
                document.getElementById("RemoveTask").style.top = ev.clientY + 'px';
                document.getElementById("RemoveTask").style.left = ev.clientX + 'px';
            }
            CallServer(selectedDate, '');
        }
        function ReceiveServerData(rValue) {
            // do nothing
        }
</script>

Just this code is for performing our event addition to database. For this I have created the invisible task pane. Whenever my user click on add/remove anchor which will use this JavaScript function to show our hidden control for collecting data from user. In the add TaskPane there is button control which will raise the event to add gathered data to database.

    protected void btnadd_Click(object sender, EventArgs e)
    {
        try
        {
            DateTime selDate = DateTime.Parse(Session["SelectedDate"] as String);
            if (AddEvents(selDate, txtTitle.Text, backcolore.SelectedItem.Text.ToString(), forecolor.SelectedItem.Text.ToString()))
            {
                txtTitle.Text = String.Empty;
                forecolor.SelectedIndex = 0;
                backcolore.SelectedIndex = 0;
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message.ToString());
        }
    }
    /// <summary>
    /// Adding Event To DataBase
    /// </summary>
    /// <param name="selDate">Date Of Event</param>
    /// <param name="p">Title Of Event</param>
    /// <param name="p_3">BackColor For The Event</param>
    /// <param name="p_4">Fore Color For The Event</param>
    /// <returns></returns>
    private bool AddEvents(DateTime selDate, string p, string p_3, string p_4)
    {
        //You can Add Those Event In Same Dataset Again Or use Any One Of The Way
        //i.e. Store Your Event In DataBase Or Store It In Dataset
        SqlConnection sqlcn = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcn"].ConnectionString);
        SqlCommand sqlcmd = new SqlCommand("Insert Into Tbl_EventDetails(EventDesc,EventDate,BackColor,ForeColor) Values('" + p + "','" + selDate + "','" + p_3 + "','" + p_4 + "')",sqlcn);
        sqlcn.Open();
        sqlcmd.CommandType = CommandType.Text;
        int _record;
        _record = sqlcmd.ExecuteNonQuery();
        if (_record > 0)
            return true;
        else
            return false;
    }
    protected void btnremove_Click(object sender, EventArgs e)
    {
        try
        {
            DateTime selDate = DateTime.Parse(Session["SelectedDate"] as String);
            if (DeleteEvant(selDate))
            {
                Response.Write("Event Deleted");
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message.ToString());
        }
    }
    private bool DeleteEvant(DateTime selDate)
    {
        //Delete Event Here From A DataBase
        return true;
    }

Conclusion:

In this manner you can create the event calender by adding some extra functionality to the code. Whatever you want to do you can do.

COMMENT USING

Trending up