Quantcast
Channel: Try MySite.GetContent() Catch(Useless Info) Finally Site.Close() End Try
Viewing all articles
Browse latest Browse all 10

Cool Tricks With The ASP.net Calendar

$
0
0

UPDATE: Additional tips: More Tips

Been A Long Time

Hello world...sorry I haven't posted in quite some time, we've been real busy at home this Christmas season.  Anyhow I thought I would share some tricks and tips with using the calendar control before you or your company spends some change to buy a control on the internet.

What Is The ASP.NET Calendar Control

The ASP.net calendar control is simply the calendar that comes prepackaged with visual studio and is available as a standard control.  Here she is on the standard control:

And here is what the calendar control may look like:

The Problem

You have been tasked to create a time off tool request involving some pretty complicated things.  Your boss has asked for numerous features in this tool which you hoped he had never asked. 

Da Boss

 

  • I want it to highlight specific days signaling holidays or time off requests. This helps me visualize what type of day the request is.   Color coding is a plus :-).
  • I'd like some nice mouse over effect on days that are not requested.  This helps the user notice a clickable type of cell.
  • O I dunno...I'd like to not only see a monthly view, but a yearly view so that I can quickly glance over an entire year for an employee.
  • O well...I dunno...Impress me...maybe allow a user to click a day on the calendar and have it go to a page with that calendar day being selected.

Umm you know the simple things..besides you have all the tools that the company has purchased for you.

You

Thoughts to self: ***O NO NOT THE CALENDAR CONTROL...BUT CANT WE JUST BUY SOMETHING PRE MADE***

Boss

O by the way...we don't have any money to buy any third party tools...have a great day.  Don't forget to e-mail when its all done.

You

O certainly boss...*cringe*...this should be no sweat *thank God I wore deodorant*.  Quickly images begin flashing in your head about what your boss said:

"I want it to highlight specific days signaling holidays or time off requests. This helps me visualize what type of day the request is.   Color coding is a plus :-)."

"I'd like some nice mouse over effect on days that are not requested.  This helps the user notice a clickable type of cell."

"O I dunno...I'd like to not only see a monthly view, but a yearly view so that I can quickly glance over an entire year for an employee."

"O well...I dunno...Impress me...maybe allow a user to click a day on the calendar and have it go to a page with that calendar day being selected."

**Ok that one is simple response.redirect and send a query string**

How in the world am I going to do all of these with the ASP.net calendar control?  That control is just so dull, so plain, difficult to use. 

Got To Get To Work

Well the ASP.net calendar control is pretty limited, its got a few events you can hook onto.  In fact when I started writing code using this control I was pretty upset because the control just seemed plain, really stale, didn't live up to my expectations.  But I was forced to use it.  Sure you can probably spend 100-200 bucks on a RAD Control...but do you really need to.  Most everything the Boss wants is right there in the calendar control.  So lets tackle it one step at a time.

Lets do the simple one first.  Before we begin, I am putting a caution that this code may need to be cleaned, this could o r could not be production code, it is merely a sample.  Samples help beginners and even advanced programmers learn how they can accomplish a specific task.  So take what you need and modify to fit your needs.  DO NOT EMAIL ME SAYING HOW BAD / GOOD IT IS TO DO A SPECIFIC THING.  TAKE WHAT YOU NEED AND RUN!!!  Ok done with the rant.  Now lets take the simple example of how to create the rollover effect of the calendar.

Rollover Effect

At first you might think to use the PreRender event to handle this.  The problem with the PreRender event in this case will cause your entire calendar to highlight a specific color when you roll over it.  To avoid this let's use the DayRender event this will ensure that the rollover effect is per day and not per calendar.  To do this first decide what color you want to use to highlight the calendar when you rollover it (onMouseOver).  Then decide what color you want to highlight when you are off of the calendar day (onMouseOut).

In this case I will use a light shade of blue (almost a baby blue) as the onMouseOver color and I'll use white for the onMouseOut color.  You can use hex codes or named colors, both work using this code.  You can also obtain the default backcolor property using @BackColor.

Heres some vb.net to help you:


 

 Protected Sub Calendar13_DayRender(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DayRenderEventArgs) Handles Calendar13.DayRender
 	 Dim onmouseoverStyle As String = "this.style.backgroundColor='#D4EDFF'"
	 Dim onmouseoutStyle As String = "this.style.backgroundColor='@BackColor'"
	 Dim rowBackColor As String = String.Empty
            
	 e.Cell.Attributes.Add("onmouseover", onmouseoverStyle)
	 e.Cell.Attributes.Add("onmouseout", onmouseoutStyle.Replace("@BackColor", rowBackColor))
    
     If Not e.Day.IsWeekend Then
                e.Cell.Attributes.Add("onmouseover", onmouseoverStyle)
                e.Cell.Attributes.Add("onmouseout", onmouseoutStyle.Replace("@BackColor", rowBackColor))
     End If
 End Sub

 So here all you're doing is setting a mouseOver for days that are not weekends.  The result:

Ok so now that we are done with the highlight effect lets look at the example of color coding specific days. 

Color Coding Specific Days In The ASP.net Calendar Control

In this case I assume the reader knows how to use datatables, datasets, and common sql statements such as SELECT, INSERT, UPDATE, etc.  So assume you have a table that has time off requests.  In this table you have a field where you store the time off request date.  You want the days requested off visually displayed on the calendar control in a different color.  To do this you simply write a stored procedure to pull your data.  You then store this data inside of a datatable or a dataset.  Once you have done this you check the e.Day.Date property with the value stored in your data row value.  If the values match you handle this event and you change the e.Cell.BackColor.

In my case I will use a dataset that is stored in a session variable.  You do not need to do it like this, this is just an example.  For instance, you may want to use a data table, or maybe you just want a dataset but you do not want to store it in a session variable.  In any event you preform this code yet again in the DayRender event of the calendar control.

Here is some code that will help make more sense:

 


Protected Sub Calendar13_DayRender(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DayRenderEventArgs) Handles Calendar13.DayRender 

        Dim nextDate As DateTime
 
        Try
               'this part is the actual time off requests
            If Not CType(Session("dsRequests"), DataSet) Is Nothing Then
                For Each dr As DataRow In CType(Session("dsRequests"), DataSet).Tables(0).Rows
                    nextDate = CType(dr("VacationDate"), DateTime)
                    If nextDate = e.Day.Date Then
                        e.Cell.BackColor = System.Drawing.ColorTranslator.FromHtml(CType(dr("HTMLColor"), String))
                  End If
                Next
            End If
 
        Catch ex As Exception
            Response.Write("Errors occurred: No RuleID / Hire Date specified for user! " & "Additional errors include: " & ex.ToString())
        End Try
    End Sub

What's going on in this code.  Well first and foremost get rid of what you don't need and change field names, code based on your needs.  In my table I store a field called VacationDate this field has the date value of the time off request.  I assign this value to nextDate and compare nextDate with e.Day.Date.  If these values are the same then I set the e.Cell.BackColor to a color based on another field in my database HTMLColor.  You do not have to have this field, this field is used because in my circumstances we have many time off request types and I want to associate a hex color with each time off type.  You may want to only use a specific color like, System.Drawing.Color.Red.  In this case you would do:

e.Cell.BackColor =  System.Drawing.Color.Red

So the steps are:

  1. Pull the data using a stored procedure, order it by date asc
  2. Take this data and store it in a dataset or a datatable
  3. Use the DayRender event to handle the event each day
  4. Check if e.Day.Date is equal to your date that was returned from the database (dr("HolidayDate") from above)
  5. If the values match up set the e.Cell.BackColor property to the color you want.  Better yet store a color hex value in your database for each type of time off request.

But I Used The DayRender Event For That OnMouseOver Effect Now What?

Simple, combine both together like so:

    Protected Sub Calendar13_DayRender(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DayRenderEventArgs) Handles Calendar13.DayRender
        Dim nextDate As DateTime
        Dim onmouseoverStyle As String = "this.style.backgroundColor='#D4EDFF'"
        Dim onmouseoutStyle As String = "this.style.backgroundColor='@BackColor'"
        Dim rowBackColor As String = String.Empty
        Dim notTouched As Boolean

        notTouched = True

        Try
            If Not CType(Session("dsHolidays"), DataSet) Is Nothing Then
                For Each dr As DataRow In CType(Session("dsHolidays"), DataSet).Tables(0).Rows
                    nextDate = CType(dr("HolidayDate"), DateTime)
                    If nextDate = e.Day.Date Then
                        e.Cell.BackColor = System.Drawing.Color.Pink
                        notTouched = False
                    End If
                Next
            End If

            If Not CType(Session("dsRequests"), DataSet) Is Nothing Then
                For Each dr As DataRow In CType(Session("dsRequests"), DataSet).Tables(0).Rows
                    nextDate = CType(dr("VacationDate"), DateTime)
                    If nextDate = e.Day.Date Then
                        e.Cell.BackColor = System.Drawing.ColorTranslator.FromHtml(CType(dr("HTMLColor"), String))
                        notTouched = False
                  End If
                Next
            End If

            If notTouched And Not e.Day.IsWeekend Then
                e.Cell.Attributes.Add("onmouseover", onmouseoverStyle)
                e.Cell.Attributes.Add("onmouseout", onmouseoutStyle.Replace("@BackColor", rowBackColor))
            End If

        Catch ex As Exception
            Response.Write("Errors occurred: No RuleID / Hire Date specified for user!  " & "Additional errors include: " & ex.ToString())
        End Try

    End Sub

 
The OnMouseOver effect as well as the colored background cells on the 7th and the 25th of December 07.
 
But What If I Am Using More Then One Calendar Control
 
There is always those what if's.  You may be using more then one calendar control in your application, if you are no problem.  In this case create a sub routine to HANDLES all the calendar objects in your application.  For instance, assume you have 12 calendar controls then your subroutine signature should look like this:
 

Private Sub DayRender(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DayRenderEventArgs) Handles Calendar1.DayRender, Calendar2.DayRender, _ 
                          Calendar3.DayRender, Calendar4.DayRender, Calendar5.DayRender, Calendar6.DayRender, Calendar7.DayRender, Calendar8.DayRender, Calendar9.DayRender, _
                          Calendar10.DayRender, Calendar11.DayRender, Calendar12.DayRender

This shows one sub routine called DayRender which can handle the DayRender event of any of the 12 calendars.
The rest of the code is very similiar to what we posted previously:

Private Sub DayRender(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DayRenderEventArgs) Handles Calendar1.DayRender, Calendar2.DayRender, _ 
                          Calendar3.DayRender, Calendar4.DayRender, Calendar5.DayRender, Calendar6.DayRender, Calendar7.DayRender, Calendar8.DayRender, Calendar9.DayRender, _
                          Calendar10.DayRender, Calendar11.DayRender, Calendar12.DayRender
 
        Dim nextDate As DateTime
        Dim cal As Calendar = CType(sender, Calendar)
        Dim onmouseoverStyle As String = "this.style.backgroundColor='#D4EDFF'"
        Dim onmouseoutStyle As String = "this.style.backgroundColor='@BackColor'"
        Dim rowBackColor As String = String.Empty
        Dim notTouched As Boolean
 
        notTouched = True
 
        If e.Day.Date.Month <> cal.TodaysDate.Month Then Exit Sub
 
        Try
            If Not CType(Session("dsRequests"), DataSet) Is Nothing Then
                For Each dr As DataRow In CType(Session("dsRequests"), DataSet).Tables(0).Rows
                    nextDate = CType(dr("VacationDate"), DateTime)
                    If nextDate = e.Day.Date Then
                        e.Cell.BackColor = System.Drawing.ColorTranslator.FromHtml(CType(dr("HTMLColor"), String))
                        notTouched = False
                    End If
                Next
            End If
 
            If notTouched And Not e.Day.IsWeekend Then
                e.Cell.Attributes.Add("onmouseover", onmouseoverStyle)
                e.Cell.Attributes.Add("onmouseout", onmouseoutStyle.Replace("@BackColor", rowBackColor))
            End If
 
        Catch ex As Exception
            Response.Write("Errors occurred: No RuleID / Hire Date specified for user! " & "Additional errors include: " & ex.ToString())
        End Try
    End Sub

In this case we handle all 12 calendar controls.  The result is as follows:

Passing The Date To Another Page

Suppose you want to pass a calendar day to a Response.Redirect to another page when you click on a calendar day.  Here you can simply pass a parameter to a page like so:

Response.Redirect("entry.aspx?VacationDate=" & CType(Calendar13.SelectedDate, Date))

And to pull that date in the entry.aspx page simply use the following:


Dim d as Date

d = CType(Request("VacationDate"), Date) 'grab date


Hope this helps someone out there who needs to do something similiar.  


Viewing all articles
Browse latest Browse all 10

Trending Articles