Calendar Day_Render Help!

asp_net2
asp_net2 used Ask the Experts™
on
Hello EE,

I need to be able to display different colors in the Calendar's Cell's for different values that may be stored in my table named WellnessChoice_PhysicalActivityLog in my DB. From what I read it appears that I need to use the Day_Render Event but I have never used the Calendar Control and not sure how to tie this together.

For Example, below is an actuall example of the data in my WellnessChoice_PhysicalActivityLog Table. I need to be able to display a different Calendar Cell for each different palv_id. So if for example the palv_id = 4 then display that Cell Color Blue, if palv_id = 7 then display that Cell Color Red. etc....

pal_id          palv_id           pi_id              pal_date
4000             4                   1277             2011-08-08 00:00:00.000
4001      7      1277      2011-08-12 00:00:00.000
4002             8                    1277             2011-08-23 00:00:00.000
4003             9                    1277             2011-08-29 00:00:00.000
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2013

Commented:
When do you should your calendar and how is it tied to the palv_id and the table?
Here is usine DayRender event:
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
    {
        if(palv_id==4){
            e.Cell.BackColor = System.Drawing.Color.Blue;
        }
        else if (palv_id = 5)
        {
            //something
        }
    }

Open in new window

Author

Commented:
Hi guru sami,

First of all, thank you for answering this post. I have had alot of trouble finding an answer to this online. Please see my code below. I have never worked with the Calendar Control in this way so i don't know where to start and please forgive me if i ask stupid questions.

I'm not sure if I went about this the right way but I assumed that i had to capture the data first in order to display it on the DayRender Event.

What I'm trying to accomplish is to color the Calendar Cell a different color for each different palv_id and then display the palv_name in the Cell. Keeping in mind that  user may have multiple palv_id and palv_name for a date.

CODEBEHIND:

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void RetrieveDatesForCalendarValues()
    {
        if (!IsPostBack)
        {
            int pi_id = Convert.ToInt32(Session["pi_id"]);

            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[""].ConnectionString);

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "WellnessChoice_RetrieveDatesForCalendar";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;

            cmd.Parameters.AddWithValue("@pi_id", SqlDbType.Int).Value = pi_id;

            DataTable dtDates = new DataTable();

            SqlDataAdapter adp = new SqlDataAdapter();

            try
            {
                conn.Open();

                adp.SelectCommand = cmd;
                adp.Fill(dtDates);

                //if ((dtDates != null))
                //{
                //    DataRow data = dtDates.Rows[0];
                //    hf_pal_id.Value = data["pal_id"].ToString();

                //    if (data["palv_id"].ToString() == "4")
                //    {
                //    }

                //    if (data["palv_id"].ToString() == "7")
                //    {
                //    }

                //    if (data["palv_id"].ToString() == "9")
                //    {
                //    }

                //    if (data["palv_id"].ToString() == "11")
                //    {
                //    }

                //    else
                //    {
                //        // Not sure if I need anything here
                //        // and if so what.
                //    }
                //}
            }

            catch (Exception ex)
            {
            }

            finally
            {
                conn.Close();
            }
        }
    }

        protected void DayRender(object sender, DayRenderEventArgs e)
        {

        }

Author

Commented:
Sorry, I forgot to include the Stored Procedure (SP) that I'm using. Also, please see the following data that the SP displays to give you an idea.

pi_id      palv_id      pal_date                               palv_names
1277      4      2011-08-08 00:00:00.000          Boxing/Karate
1277      7      2011-08-12 00:00:00.000          Elliptical
1277      9      2011-08-20 00:00:00.000          Zumba
1277      11      2011-08-22 00:00:00.000          Aerobics/Pilates



ALTER PROCEDURE [dbo].[WellnessChoice_RetrieveDatesForCalendar]

(
@pi_id int
)

AS

SELECT pal.pi_id, pal.palv_id, pal.pal_date, palv.palv_names
FROM WellnessChoice_PhysicalActivityLog AS pal
INNER JOIN WellnessChoice_PhysicalActivityLogValues AS palv
ON pal.palv_id = palv.palv_id
WHERE pi_id = @pi_id
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

Commented:
Couple examples:

http://weblogs.sqlteam.com/jhermiz/archive/2007/12/10/Cool-Tricks-With-The-ASP.net-Calendar.aspx
http://www.java2s.com/Code/ASP/Asp-Control/CalendarcontrolincodebehindC.htm

I would take your pal_date and grab the date and month from it like so:

http://msdn.microsoft.com/en-us/library/system.datetime.day.aspx#Y1100
(i used the example at the bottom moment.Month etc...)

and then do something like this in your Calendar_DayRender method:



if (e.Day.Date.Day == moment.Day && e.Day.Date.Month == moment.Month)
      {
        e.Cell.BackColor = System.Drawing.Color.Yellow;

        // Add some static text to the cell.
        Label lbl = new Label();
        lbl.Text = "<br>"; // put palv_names here?
        e.Cell.Controls.Add(lbl);
      }

Open in new window

Commented:
you can also generator a random color like so as well:

http://www.jpreece.com/csharp/random-color-generator/

Author

Commented:
Hi disrupt,

sorry, but I don't understand what you are trying to say. I did enjoy the link with 12 Calendar Controls, that is what I was asked to do was to dislay 12 calendar controls but I need to at least display a BG color for each different palv_id and also display the palv_name in that cell. Could you help me with the code that i supplied?

Thanks in advance!

Commented:
something like this...
protected void Page_Load(object sender, EventArgs e)
    {

    }

   protected void DayRender(object sender, DayRenderEventArgs e)
    {
        if (!IsPostBack)
        {
            int pi_id = Convert.ToInt32(Session["pi_id"]);

            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[""].ConnectionString);

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "WellnessChoice_RetrieveDatesForCalendar";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;

            cmd.Parameters.AddWithValue("@pi_id", SqlDbType.Int).Value = pi_id;

            DataTable dtDates = new DataTable();

            SqlDataAdapter adp = new SqlDataAdapter();

            try
            {
                conn.Open();

                adp.SelectCommand = cmd;
                adp.Fill(dtDates);
				
				

                if ((dtDates != null)) {
				
				DataRow data = dtDates.Rows[0];
				
				System.DateTime pal = Convert.ToDateTime(data["pal_date"]);
				
				if (e.Day.Date.Day == pal.Day && e.Day.Date.Month == pal.Month)
                   {
                      e.Cell.BackColor = System.Drawing.Color.Yellow;
					         Label lbl = new Label();
                             lbl.Text = "<br>" + data["palv_names"].toString();
                             e.Cell.Controls.Add(lbl);

    			   }
				
				}
				
			
            }
            }

            catch (Exception ex)
            {
            }

            finally
            {
                conn.Close();
            }
        }

Open in new window

Commented:
string[,] palArr = null;


void page_Load(......){
  if (!IsPostBack)
        {
getPalDates();
        }
}


//GET AVAILABLE DATE AND ITS CORRESPONDING NAME IN AN ARRAY

sub getPalDates(){
            int pi_id = Convert.ToInt32(Session["pi_id"]);

            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[""].ConnectionString);

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "WellnessChoice_RetrieveDatesForCalendar";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;

            cmd.Parameters.AddWithValue("@pi_id", SqlDbType.Int).Value = pi_id;

            DataTable dtDates = new DataTable();

            SqlDataAdapter adp = new SqlDataAdapter();

            try
            {
                conn.Open();

                adp.SelectCommand = cmd;
                adp.Fill(dtDates);
                palArr = new string[13,32];
               for (int iCnt = 0; iCnt <= dt.Rows.Count - 1; iCnt++) {
                     MyCal.SelectedDates.Add(dt.Rows[iCnt].Item["pal_date"]);
                        DateTime dm = dt.Rows[iCnt].Item["pal_date"];
                        palArr[dm.Month, dm.Day] = dt.Rows[iCnt].Item["palv_names"] + "|" +dt.Rows[iCnt].Item["palv_id"] ;
                         }
          }


catch (Exception ex)
            {
            }

}


//CUSTOMIZE UR CALENDAR RENDER EVENT NOW

protected void MyCal_DayRender(object sender, System.Web.UI.WebControls.DayRenderEventArgs e)
{
      CalendarDay day = (CalendarDay)e.Day;
      TableCell cell = (TableCell)e.Cell;

      if (!day.IsOtherMonth) {
            string palName = palArr(day.Date.Month, day.Date.Day);

            if (palName != null) {
                                 var p = palName.split("|");
                                 if(p[1]==4){
                                              e.Cell.BackColor = System.Drawing.Color.Yellow;
                                 }else if( p[1]==7){
                                              e.Cell.BackColor = System.Drawing.Color.Blue;
                                 }//etc...
                        Label lbl = new Label();
                             lbl.Text = "<br>" +p[0];
                             e.Cell.Controls.Add(lbl);
            }
      }
}


Commented:
sorry , use

string[,] palArr = null;


void page_Load(......){
  if (!IsPostBack)
        {
getPalDates();
        }
}


//GET AVAILABLE DATE AND ITS CORRESPONDING NAME IN AN ARRAY

sub getPalDates(){
            int pi_id = Convert.ToInt32(Session["pi_id"]);

            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[""].ConnectionString);

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "WellnessChoice_RetrieveDatesForCalendar";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;

            cmd.Parameters.AddWithValue("@pi_id", SqlDbType.Int).Value = pi_id;

            DataTable dtDates = new DataTable();

            SqlDataAdapter adp = new SqlDataAdapter();

            try
            {
                conn.Open();

                adp.SelectCommand = cmd;
                adp.Fill(dtDates);
                palArr = new string[13,32];
               for (int iCnt = 0; iCnt <= dt.Rows.Count - 1; iCnt++) {
                     MyCal.SelectedDates.Add(dt.Rows[iCnt].Item["pal_date"]);
                        DateTime dm = dt.Rows[iCnt].Item["pal_date"];
                        palArr[dm.Month, dm.Day] = dt.Rows[iCnt].Item["palv_names"] + "|" +dt.Rows[iCnt].Item["palv_id"] ;
                         }
          }


catch (Exception ex)
            {
            }

}


//CUSTOMIZE UR CALENDAR RENDER EVENT NOW

protected void MyCal_DayRender(object sender, System.Web.UI.WebControls.DayRenderEventArgs e)
{
      CalendarDay day = (CalendarDay)e.Day;
      TableCell cell = (TableCell)e.Cell;

      if (!day.IsOtherMonth) {
            string palName = palArr(day.Date.Month, day.Date.Day);

            if (palName != null) {
                                 var p = palName.split("|");
                                 if(p[1]==4){
                                              e.Cell.BackColor = System.Drawing.Color.Yellow;
                                 }else if( p[1]==7){
                                              e.Cell.BackColor = System.Drawing.Color.Blue;
                                 }//etc...
                        Label lbl = new Label();
                             lbl.Text = "<br>" +p[0];
                             e.Cell.Controls.Add(lbl);
            }
      }
}

Open in new window

Author

Commented:
@dejaanbu,

I used your last code in your post but have a few errors highlighted in red. Please see my code below and the messages that i'm receiving along with there lines of code.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ApplicationProcess_Secure_PhysicalActivityLog : System.Web.UI.Page
{
    string[,] palArr = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            getPalDates();
        }
    }

    //GET AVAILABLE DATE AND ITS CORRESPONDING NAME IN AN ARRAY
    protected void getPalDates()
    {
        int pi_id = Convert.ToInt32(Session["pi_id"]);

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[""].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "WellnessChoice_RetrieveDatesForCalendar";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        cmd.Parameters.AddWithValue("@pi_id", SqlDbType.Int).Value = pi_id;

        DataTable dtDates = new DataTable();

        SqlDataAdapter adp = new SqlDataAdapter();

        try
        {
            conn.Open();

            adp.SelectCommand = cmd;
            adp.Fill(dtDates);
            palArr = new string[13, 32];
            for (int iCnt = 0; iCnt <= dtDates.Rows.Count - 1; iCnt++)
            {
                Calendar1.SelectedDates.Add(dtDates.Rows[iCnt].Item["pal_date"]);
                DateTime dm = dtDates.Rows[iCnt].Item["pal_date"];
                palArr[dm.Month, dm.Day] = dtDates.Rows[iCnt].Item["palv_names"] + "|" + dtDates.Rows[iCnt].Item["palv_id"];
            }
        }

        catch (Exception ex)
        {
        }

        finally
        {
            conn.Close();
        }

    }

    //CUSTOMIZE UR CALENDAR RENDER EVENT NOW
    protected void MyCal_DayRender(object sender, System.Web.UI.WebControls.DayRenderEventArgs e)
    {
        CalendarDay day = (CalendarDay)e.Day;
        TableCell cell = (TableCell)e.Cell;

        if (!day.IsOtherMonth)
        {
            string palName = palArr(day.Date.Month, day.Date.Day);

            if (palName != null)
            {
                var p = palName.split("|");
                if (p[1] == 4)
                {
                    e.Cell.BackColor = System.Drawing.Color.Yellow;
                }
                else if (p[1] == 7)
                {
                    e.Cell.BackColor = System.Drawing.Color.Blue;
                }//etc...
                Label lbl = new Label();
                lbl.Text = "<br>" + p[0];
                e.Cell.Controls.Add(lbl);
            }
        }
    }

}



LINES WITH RED LINE MESSAGE:
Calendar1.SelectedDates.Add(dtDates.Rows[iCnt].Item["pal_date"]);
                DateTime dm = dtDates.Rows[iCnt].Item["pal_date"];
                palArr[dm.Month, dm.Day] = dtDates.Rows[iCnt].Item["palv_names"] + "|" + dtDates.Rows[iCnt].Item["palv_id"];

ERROR MESSAGE:
'System.Data.DataRow' does not contain a definition for 'Item' and no extension method 'Item' accepting a first argument of type 'system.data.datarow' could be found (are you missing a using directive or an assembly reference?)

LINE WITH RED MESSAGE:
string palName = palArr(day.Date.Month, day.Date.Day);

ERROR MESSAGE:
The name 'palArr' does not exist in the current context.

LINE WITH RED MESSAGE:
var p = palName.split("|");

ERROR MESSAGE:
'String' does not contain a definition for 'split' and no extension method 'split' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)

Author

Commented:
To all of you, the following link below is what I'm trying to accomplish. I was just asked if I could display a page with all calendars for the year 2011 and then display calendars for 2012 once 2011 is over. I found this link below but not sure how to set it up. I do need the ability at some point to be able to click a day and then have a popup display so that I can entered values into the DB but for now I would just like to be able to display a different color for each different value in the palv_id field.

Also, I'm worried about performance if I would use 12 calendar controls. Could I just use one calendar control and display the same results if the user chooses to click through the different months?

http://weblogs.sqlteam.com/jhermiz/archive/2007/12/10/Cool-Tricks-With-The-ASP.net-Calendar.aspx

Commented:
Oops.. thats a VB Syntax.. sorry... since i am not a C# Guy....

for this line dtDates.Rows[iCnt].Item["pal_date"];   make it as

dtDates.Rows[iCnt]["pal_date"];    -> remove   .item

make like that in all lines wherever item error comes

for other errors, i'll post the soln again

Author

Commented:
That does not seem to help either dejaanbu. Even more red lines with errors.

Commented:
string palName = palArr(day.Date.Month, day.Date.Day);

should be

string palName = palArr[day.Date.Month, day.Date.Day];


var p = palName.split("|");

should be

var p = palName.Split("|");

post the error that occurs after the last change i suggested

Author

Commented:
LINES OF CODE WITH RED LINE:
Calendar1.SelectedDates.Add(dtDates.Rows[iCnt].Item["pal_date"]);
DateTime dm = dtDates.Rows[iCnt].Item["pal_date"];
palArr[dm.Month, dm.Day] = dtDates.Rows[iCnt].Item["palv_names"] + "|" + dtDates.Rows[iCnt].Item["palv_id"];

ERROR MESSAGE:
'System.Data.DataRow' does not contain a definition for 'Item' and no extension method 'Item' accepting a first argument of type 'system.data.datarow' could be found (are you missing a using directive or an assembly reference?)

CODE WITH RED ERROR:
var p = palName.Split("|");

ERROR MESSAGE:
(Local Variable) string palName
The best overload method match for 'string.split (params char[])' has  some invalid arguments

CODE WITH RED ERROR:
else if (p[1] == 7)

ERROR MESSAGE:
Operator '==' cannot be applied to operands of type 'string' and 'int'

CODE WITH RED ERROR:
else if (p[1] == 7)

UPDATED CODE BELOW:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ApplicationProcess_Secure_PhysicalActivityLog : System.Web.UI.Page
{
    string[,] palArr = null;


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            getPalDates();
        }
    }


    //GET AVAILABLE DATE AND ITS CORRESPONDING NAME IN AN ARRAY
    protected void getPalDates()
    {
        int pi_id = Convert.ToInt32(Session["pi_id"]);

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[""].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "WellnessChoice_RetrieveDatesForCalendar";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        cmd.Parameters.AddWithValue("@pi_id", SqlDbType.Int).Value = pi_id;

        DataTable dtDates = new DataTable();

        SqlDataAdapter adp = new SqlDataAdapter();

        try
        {
            conn.Open();

            adp.SelectCommand = cmd;
            adp.Fill(dtDates);
            palArr = new string[13, 32];
            for (int iCnt = 0; iCnt <= dtDates.Rows.Count - 1; iCnt++)
            {
                Calendar1.SelectedDates.Add(dtDates.Rows[iCnt].Item["pal_date"]);
                DateTime dm = dtDates.Rows[iCnt].Item["pal_date"];
                palArr[dm.Month, dm.Day] = dtDates.Rows[iCnt].Item["palv_names"] + "|" + dtDates.Rows[iCnt].Item["palv_id"];
            }
        }

        catch (Exception ex)
        {
        }

        finally
        {
            conn.Close();
        }

    }

    //CUSTOMIZE UR CALENDAR RENDER EVENT NOW
    protected void MyCal_DayRender(object sender, System.Web.UI.WebControls.DayRenderEventArgs e)
    {
        CalendarDay day = (CalendarDay)e.Day;
        TableCell cell = (TableCell)e.Cell;

        if (!day.IsOtherMonth)
        {
            string palName = palArr[day.Date.Month, day.Date.Day];

            if (palName != null)
            {
                var p = palName.Split("|");
                if (p[1] == 4)
                {
                    e.Cell.BackColor = System.Drawing.Color.Yellow;
                }
                else if (p[1] == 7)
                {
                    e.Cell.BackColor = System.Drawing.Color.Blue;
                }//etc...
                Label lbl = new Label();
                lbl.Text = "<br>" + p[0];
                e.Cell.Controls.Add(lbl);
            }
        }
    }

}

Commented:
as i told,  dtDates.Rows[iCnt].Item["pal_date"];, should be

dtDates.Rows[iCnt]["pal_date"];

similarly, dtDates.Rows[iCnt].Item["palv_names"] must be

dtDates.Rows[iCnt]["palv_names"];

dtDates.Rows[iCnt].Item["palv_id"];, should be

dtDates.Rows[iCnt]["palv_id"];



if (p[1] == 4)  ..pls change to..

if (p[1].ToString() == "4")

else if (p[1] == 7).. change to

else if (p[1].ToString() =="7")


THEN

var p = palName.Split("|");  ...please change to

var p = palName.Split('|');


OMG..what a strict C#!..Sorry Again.......



Author

Commented:
yeah, C# is VERY Strict.

Ok, please see different error message:

LINE OF CODE WITH RED LINE MESSAGE:
Calendar1.SelectedDates.Add(dtDates.Rows[iCnt]["pal_date"];);

ERROR MESSAGE:
The best overloaded method match for 'system.web.ui.webcontrols.selecteddatescollection.add (system.datetime)' has some invalid arguments.

LINE OF CODE WITH RED LINE MESSAGE:
DateTime dm = dtDates.Rows[iCnt]["pal_date"];

ERROR MESSAGE:
Cannot implicity convert type 'object' to 'system.datetime'. An explicit conversion exists (are you missing a cast?)

LINE OF CODE WITH RED LINE MESSAGE:
palArr[dm.Month, dm.Day] = dtDates.Rows[iCnt]["palv_names"]; + "|" + dtDates.Rows[iCnt]["palv_id"];

ERROR MESSAGE:
Cannot implicity convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)


UPDATED CODE:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ApplicationProcess_Secure_PhysicalActivityLog : System.Web.UI.Page
{
    string[,] palArr = null;


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            getPalDates();
        }
    }


    //GET AVAILABLE DATE AND ITS CORRESPONDING NAME IN AN ARRAY
    protected void getPalDates()
    {
        int pi_id = Convert.ToInt32(Session["pi_id"]);

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[""].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "WellnessChoice_RetrieveDatesForCalendar";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        cmd.Parameters.AddWithValue("@pi_id", SqlDbType.Int).Value = pi_id;

        DataTable dtDates = new DataTable();

        SqlDataAdapter adp = new SqlDataAdapter();

        try
        {
            conn.Open();

            adp.SelectCommand = cmd;
            adp.Fill(dtDates);
            palArr = new string[13, 32];
            for (int iCnt = 0; iCnt <= dtDates.Rows.Count - 1; iCnt++)
            {
                Calendar1.SelectedDates.Add(dtDates.Rows[iCnt]["pal_date"];);
                DateTime dm = dtDates.Rows[iCnt]["pal_date"];
                palArr[dm.Month, dm.Day] = dtDates.Rows[iCnt]["palv_names"]; + "|" + dtDates.Rows[iCnt]["palv_id"];
            }
        }

        catch (Exception ex)
        {
        }

        finally
        {
            conn.Close();
        }

    }

    //CUSTOMIZE UR CALENDAR RENDER EVENT NOW
    protected void MyCal_DayRender(object sender, System.Web.UI.WebControls.DayRenderEventArgs e)
    {
        CalendarDay day = (CalendarDay)e.Day;
        TableCell cell = (TableCell)e.Cell;

        if (!day.IsOtherMonth)
        {
            string palName = palArr[day.Date.Month, day.Date.Day];

            if (palName != null)
            {
                var p = palName.Split('|');
                if (p[1].ToString() == "4")
                {
                    e.Cell.BackColor = System.Drawing.Color.Yellow;
                }
                else if (p[1].ToString() == "7")
                {
                    e.Cell.BackColor = System.Drawing.Color.Blue;
                }//etc...
                Label lbl = new Label();
                lbl.Text = "<br>" + p[0];
                e.Cell.Controls.Add(lbl);
            }
        }
    }

}

Commented:
Calendar1.SelectedDates.Add(dtDates.Rows[iCnt]["pal_date"];); should be

Calendar1.SelectedDates.Add(Convert.ToDateTime(dt.Rows[0]["pal_date"]));

DateTime dm = dtDates.Rows[iCnt]["pal_date"];  should be

DateTime dm = Convert.ToDateTime(dtDates.Rows[iCnt]["pal_date"]);

palArr[dm.Month, dm.Day] = dtDates.Rows[iCnt]["palv_names"]; + "|" + dtDates.Rows[iCnt]["palv_id"];
 should be

palArr[dm.Month, dm.Day] = dtDates.Rows[iCnt]["palv_names"].ToString() + "|" + dtDates.Rows[iCnt]["palv_id"].ToString();

Author

Commented:
Ok, that worked but with a another issue. If I where to select another month from the Calendar Control to see values for another month then I get the following Error Message from the line of code below.

CODE WITH ERROR:
string palName = palArr[day.Date.Month, day.Date.Day];

ERROR MESSAGE:
Object reference not set to an instance of an object.


UPDATED CODE:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ApplicationProcess_Secure_PhysicalActivityLog : System.Web.UI.Page
{
    string[,] palArr = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            getPalDates();
        }
    }

    //GET AVAILABLE DATE AND ITS CORRESPONDING NAME IN AN ARRAY
    protected void getPalDates()
    {
        int pi_id = Convert.ToInt32(Session["pi_id"]);

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessChoice"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "WellnessChoice_RetrieveDatesForCalendar";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        cmd.Parameters.AddWithValue("@pi_id", SqlDbType.Int).Value = pi_id;

        DataTable dtDates = new DataTable();

        SqlDataAdapter adp = new SqlDataAdapter();

        try
        {
            conn.Open();

            adp.SelectCommand = cmd;
            adp.Fill(dtDates);
            palArr = new string[13, 32];
            for (int iCnt = 0; iCnt <= dtDates.Rows.Count - 1; iCnt++)
            {
                Calendar1.SelectedDates.Add(Convert.ToDateTime(dtDates.Rows[0]["pal_date"]));
                DateTime dm = Convert.ToDateTime(dtDates.Rows[iCnt]["pal_date"]);
                palArr[dm.Month, dm.Day] = dtDates.Rows[iCnt]["palv_code"].ToString() + "|" + dtDates.Rows[iCnt]["palv_id"].ToString();
            }
        }

        catch (Exception ex)
        {
            ex.Message.ToString();
        }

        finally
        {
            conn.Close();
        }
    }

    //CUSTOMIZE UR CALENDAR RENDER EVENT NOW
    protected void MyCal_DayRender(object sender, System.Web.UI.WebControls.DayRenderEventArgs e)
    {
        CalendarDay day = (CalendarDay)e.Day;
        TableCell cell = (TableCell)e.Cell;

        if (!day.IsOtherMonth)
        {
            string palName = palArr[day.Date.Month, day.Date.Day];

            if (palName != null)
            {
                var p = palName.Split('|');
                if (p[1].ToString() == "4")
                {
                    e.Cell.BackColor = System.Drawing.Color.Crimson;
                }
                else if (p[1].ToString() == "7")
                {
                    e.Cell.BackColor = System.Drawing.Color.Coral;
                }
                else if (p[1].ToString() == "9")
                {
                    e.Cell.BackColor = System.Drawing.Color.Cornsilk;
                }
                else if (p[1].ToString() == "11")
                {
                    e.Cell.BackColor = System.Drawing.Color.Chocolate;
                }
                Label lbl = new Label();
                lbl.Text = "<br>" + p[0];
                e.Cell.Controls.Add(lbl);
            }
        }
    }

}

Commented:
 if (!day.IsOtherMonth) instead of this

 if (!day.IsOtherMonth && palArr[day.Date.Month, day.Date.Day]!=null)


but if you want to display the cell bgcolor, whenever u change the month from the calendar, you need to call the getPalDates() in calendar's selectionchanged event...i suggest you to have that DataTable in session once populated, and process next time from session.

Author

Commented:
Ok, could you assist me with storing the DataTable in Session? Also, how large or small with that Session Value be?

Author

Commented:
Hi dejaanbu,

Is it also possible to use HEX colors instead? For example #ffffff instead of White?

Author

Commented:
Hi dejaanbu,

Ok, I was able to add aRGB values as a color rather than the name itself. Please see my code below for that in the event someone else asks you.

As for the OnSelectionChanged Event I tried adding the following below but receive the following message when trying to click on the "next" and "previous" link to view other months.

LINE OF CODE THAT PRODUCES ERROR:
if (!day.IsOtherMonth && palArr[day.Date.Month, day.Date.Day] != null)

ERROR MESSAGE WHEN VIEWING OTHER MONTHS:
Object reference not set to an instance of an object.


UPDATED CODE:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ApplicationProcess_Secure_PhysicalActivityLog : System.Web.UI.Page
{
    string[,] palArr = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            getPalDates();
        }
    }

    //GET AVAILABLE DATE AND ITS CORRESPONDING NAME IN AN ARRAY
    protected void getPalDates()
    {
        int pi_id = Convert.ToInt32(Session["pi_id"]);

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessChoice"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "WellnessChoice_RetrieveDatesForCalendar";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        cmd.Parameters.AddWithValue("@pi_id", SqlDbType.Int).Value = pi_id;

        DataTable dtDates = new DataTable();

        SqlDataAdapter adp = new SqlDataAdapter();

        try
        {
            conn.Open();

            adp.SelectCommand = cmd;
            adp.Fill(dtDates);
            palArr = new string[13, 32];
            for (int iCnt = 0; iCnt <= dtDates.Rows.Count - 1; iCnt++)
            {
                Calendar1.SelectedDates.Add(Convert.ToDateTime(dtDates.Rows[0]["pal_date"]));
                DateTime dm = Convert.ToDateTime(dtDates.Rows[iCnt]["pal_date"]);
                palArr[dm.Month, dm.Day] = dtDates.Rows[iCnt]["palv_code"].ToString() + "|" + dtDates.Rows[iCnt]["palv_id"].ToString();
            }
        }

        catch (Exception ex)
        {
            ex.Message.ToString();
        }

        finally
        {
            conn.Close();
        }
    }

    //CUSTOMIZE UR CALENDAR RENDER EVENT NOW
    protected void MyCal_DayRender(object sender, System.Web.UI.WebControls.DayRenderEventArgs e)
    {
        CalendarDay day = (CalendarDay)e.Day;
        TableCell cell = (TableCell)e.Cell;

        // if (!day.IsOtherMonth)
        if (!day.IsOtherMonth && palArr[day.Date.Month, day.Date.Day] != null)

        {
            string palName = palArr[day.Date.Month, day.Date.Day];

            if (palName != null)
            {
                var p = palName.Split('|');
                if (p[1].ToString() == "2")
                {
                    e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 255, 138, 215);
                }
                else if (p[1].ToString() == "3")
                {
                    e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 255, 138, 140);
                }
                else if (p[1].ToString() == "4")
                {
                    e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 255, 181, 138);
                }
                else if (p[1].ToString() == "5")
                {
                    e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 255, 204, 138);
                }
                else if (p[1].ToString() == "6")
                {
                    e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 255, 229, 138);
                }
                else if (p[1].ToString() == "7")
                {
                    e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 255, 254, 138);
                }
                else if (p[1].ToString() == "8")
                {
                    e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 221, 255, 138);
                }
                else if (p[1].ToString() == "9")
                {
                    e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 146, 249, 134);
                }
                else if (p[1].ToString() == "10")
                {
                    e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 138, 238, 255);
                }
                else if (p[1].ToString() == "11")
                {
                    e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 136, 199, 252);
                }
                else if (p[1].ToString() == "12")
                {
                    e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 133, 146, 246);
                }
                else if (p[1].ToString() == "13")
                {
                    e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 195, 131, 242);
                }
                Label lbl = new Label();
                lbl.Text = "<br>" + p[0];
                e.Cell.Controls.Add(lbl);
            }
        }
    }

    protected void MyCal_SelectedChanged(Object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            getPalDates();
        }
    }

}

Author

Commented:
Hi dejaanbu,

I found out that I needed to use MyCal_MonthChange for the Next/Previous Months. The one thing that i still would like help with is storing the getpalDates into a Session depending on the size of that data. If it's to large than I would like to know the alternative.

Most importantly... I found an issue with the code that you helped me with. A user may have multiple activities for a day and the day is only showing one entry backColor and not the different entrys. Is it possible to either just color code the palv_name instead of making the backcolor cell change color so that we can display the multipe entrys for each day if there is one?

Commented:
if your expected data is only few rows of data, then u can process using session..if the expected data may be more than  50  lines of rows, then u keep displaying it from query..

if u can use session, then change getPalDates like this

protected void getPalDates()
    {
        int pi_id = Convert.ToInt32(Session["pi_id"]);
 DataTable dtDates = new DataTable();
if(Session["theActivityData"] !=null){
dtDates =(DataTable)Session["theActivityData"];
}else{
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessChoice"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "WellnessChoice_RetrieveDatesForCalendar";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        cmd.Parameters.AddWithValue("@pi_id", SqlDbType.Int).Value = pi_id;

       

        SqlDataAdapter adp = new SqlDataAdapter();

        try
        {
            conn.Open();

            adp.SelectCommand = cmd;
            adp.Fill(dtDates);
            if(dtDates.Rows.Count>0) Session["theActivityData"]=dtDates;
}
 catch (Exception ex)
        {
            ex.Message.ToString();
        }

        finally
        {
            conn.Close();
        }

}
            palArr = new string[13, 32];
            for (int iCnt = 0; iCnt <= dtDates.Rows.Count - 1; iCnt++)
            {
                Calendar1.SelectedDates.Add(Convert.ToDateTime(dtDates.Rows[0]["pal_date"]));
                DateTime dm = Convert.ToDateTime(dtDates.Rows[iCnt]["pal_date"]);
                palArr[dm.Month, dm.Day] = dtDates.Rows[iCnt]["palv_code"].ToString() + "|" + dtDates.Rows[iCnt]["palv_id"].ToString();
            }
        
      
    }

Open in new window


if a calendar date can have multiple entries for a single date, you have to concatenate all that activities in a single string inside the For loop in the code....u may need some sort of customization of the datatable.

Author

Commented:
>> if a calendar date can have multiple entries for a single date, you have to concatenate all that activities in a single string inside the For loop in the code....u may need some sort of customization of the datatable.

Would you be willing to assist me with this if I create another post? I just found out that that is what they need and of course don't have a clue as to what to do :(

Thank you for the code for the Session!!!

Commented:
let me confirm about ur requirement...now u r passing only one parameter to the stored procedure (pi_id)...for each month change in calendar, u need to  re-render the calendar for that month right?.. if so, is it not needed to pass the current month selected in the calendar?

i mean ur data is based on the current selected month right?? if i am right, u need to pass the current selected month to the stored procedure and only select the data for that month..let me know..

Author

Commented:
When a user logs into the system it creates a session for pi_id. A user may have several events for any given month. So if a user needs to see his/her events for December of 2011 they can click through to see which events they scheduled for.

Also, a user may have several events for a particular day. I may sign up for Walking, Running, and Swimming for 8/10/2011 and if so I need to display those events for that day and somehow color code all those different events.

If you look below pi_id 1277 may have three events that he/she signed up for on 8-1-2011 and if so I need to display the names of all three events for that day in the calendar control and either color code the different names or add a backcolor to label for each differnt name and not the calendars Cell since more than one entry may take place.

The data in the DB would look like the following:

pal_id       palv_id              pi_id               pal_date
4007      2      1277      2011-08-01
4008             4                    1277             2011-08-01
4009             8                    1277             2011-08-01
4010             5                    1277             2011-08-22

Author

Commented:
Hi dejaanbu,

Are you still able to help me with this? Not sure if we are in different Time Zones and just missing each other or not.

Thanks in advance!!

Commented:
you may need to pass not only the pi_id, but also the current month and year to the stored procedure.  so that u can get data for only that month.


once you get the datatable, you can get multiple entries for a particular user using a simple linq query
DataTable dtDates = new DataTable();  //should give you the data for current month for the current pi_id.
then for getting the multiple activities of a given user , u should do something like this

IEnumerable<DataRow> query =
    from activities in dtDates.AsEnumerable()
    where activities.Field<Int32>("pi_id")=1277; //i am passing the id by static
    select activities;
DataTable boundTable = query.CopyToDataTable<DataRow>();

now boundTable will have the activities of 1277 from the original DtDates. then you can loop through the boundTable rows and concatenate all activities to a single string.


if you feel difficulties, since this question has more comments, .. i suggest you to open another question by explaining ur requirement, so that others may come up with better solution than me.



Author

Commented:
Hi dejaanbu,

Ok, I will close this post and open another with those requirements. Before I close can you tell me why it is when I select a different month that my entries do not display?

For example:

- When Page first Loads it loads all entries for August correctly.
- When User clicks "next" or "previous" links at top of Calendar control then no other entries get displayed for the selected month.
- If I try to go back to August then all entries still do not display.

Any idea what may be causing this? Could it have something to do with PostBack and if so where?

Author

Commented:
My updated code in case you need to see what I have.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ApplicationProcess_Secure_PhysicalActivityLog : System.Web.UI.Page
{
    string[,] palArr = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        hf_AppID.Value = Session["pi_id"].ToString();

        RetrieveCalendarNames();

        if (!IsPostBack)
        {
            getPalDates();
        }
    }

    //GET AVAILABLE DATE AND ITS CORRESPONDING NAME IN AN ARRAY
    protected void getPalDates()
    {
        int pi_id = Convert.ToInt32(Session["pi_id"]);

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessChoice"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "WellnessChoice_RetrieveDatesForCalendar";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        cmd.Parameters.AddWithValue("@pi_id", SqlDbType.Int).Value = pi_id;

        DataTable dtDates = new DataTable();

        SqlDataAdapter adp = new SqlDataAdapter();

        try
        {
            conn.Open();

            adp.SelectCommand = cmd;
            adp.Fill(dtDates);
            palArr = new string[13, 32];
            for (int iCnt = 0; iCnt <= dtDates.Rows.Count - 1; iCnt++)
            {
                Calendar1.SelectedDates.Add(Convert.ToDateTime(dtDates.Rows[0]["pal_date"]));
                DateTime dm = Convert.ToDateTime(dtDates.Rows[iCnt]["pal_date"]);
                palArr[dm.Month, dm.Day] = dtDates.Rows[iCnt]["palv_code"].ToString() + "|" + dtDates.Rows[iCnt]["palv_id"].ToString();
            }
        }

        catch (Exception ex)
        {
            ex.Message.ToString();
        }

        finally
        {
            conn.Close();
        }
    }

    //CUSTOMIZE UR CALENDAR RENDER EVENT NOW
    protected void MyCal_DayRender(object sender, DayRenderEventArgs e)
    {
        // remove if (!IsPostBack) if running into Render errors
        if (!IsPostBack)
        {
            CalendarDay day = (CalendarDay)e.Day;
            TableCell cell = (TableCell)e.Cell;

            // if (!day.IsOtherMonth)
            if (!day.IsOtherMonth && palArr[day.Date.Month, day.Date.Day] != null)
            {
                string palName = palArr[day.Date.Month, day.Date.Day];

                if (palName != null)
                {
                    var p = palName.Split('|');
                    if (p[1].ToString() == "2")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 255, 138, 215);
                    }
                    else if (p[1].ToString() == "3")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 255, 138, 140);
                    }
                    else if (p[1].ToString() == "4")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 255, 181, 138);
                    }
                    else if (p[1].ToString() == "5")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 255, 204, 138);
                    }
                    else if (p[1].ToString() == "6")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 255, 229, 138);
                    }
                    else if (p[1].ToString() == "7")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 255, 254, 138);
                    }
                    else if (p[1].ToString() == "8")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 221, 255, 138);
                    }
                    else if (p[1].ToString() == "9")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 146, 249, 134);
                    }
                    else if (p[1].ToString() == "10")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 138, 238, 255);
                    }
                    else if (p[1].ToString() == "11")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 136, 199, 252);
                    }
                    else if (p[1].ToString() == "12")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 133, 146, 246);
                    }
                    else if (p[1].ToString() == "13")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 195, 131, 242);
                    }

                    Label lbl = new Label();
                    lbl.Text = "<br>" + p[0];
                    e.Cell.Controls.Add(lbl);
                }
            }
        }
    }

    protected void MyCal_MonthChange(object sender, MonthChangedEventArgs e)
    {
        getPalDates();
    }

    protected void MyCal_SelectionChanged(object sender, EventArgs e)
    {
        calendarExt.Show();

        if (!IsPostBack)
        {
            RetrieveCalendarNames();
        }
    }

    protected void RetrieveCalendarNames()
    {
        if (!IsPostBack)
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessChoice"].ConnectionString);

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "WellnessChoice_TestTest";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;

            try
            {
                conn.Open();

                SqlDataReader rdr = cmd.ExecuteReader();

                ddl_Name.DataSource = rdr;
                ddl_Name.DataValueField = "palv_id";
                ddl_Name.DataTextField = "palv_names";
                ddl_Name.DataBind();

                rdr.Close();
            }

            catch (Exception ex)
            {
                ex.Message.ToString();
            }

            finally
            {
                conn.Close();
            }
        }
    }

    protected void btn_SavePhysicalActivityLog_Click(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessChoice"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "WellnessChoice_InsertPhysicalActivityLog";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        cmd.Parameters.AddWithValue("@pi_id", SqlDbType.Int).Value = hf_AppID.Value;
        cmd.Parameters.AddWithValue("@palv_id", SqlDbType.Int).Value = ddl_Name.SelectedItem.Value;
        cmd.Parameters.AddWithValue("@pal_date", SqlDbType.DateTime).Value = Calendar1.SelectedDate.ToShortDateString();
        //cmd.Parameters.AddWithValue("@pal_id", SqlDbType.Int).Value = hf_pal_id.Value;

        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
        }

        catch (Exception ex)
        {
            // ex.Message.ToString();
            lblSaveError.Text = ("Error on insert: " + ex.Message.ToString());
        }

        finally
        {
            Response.Redirect("PhysicalActivityLog.aspx");
            conn.Close();
        }
    }
}

Author

Commented:
@dejaanbu @guru_sami disrupt:

I'm going to close this post now. But just wanted you all to know that I have another issue in regards to this post that can be found below if anyone of you would be willing to assist.

http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/Q_27251567.html

Commented:
try the following:

remove Mycal_selectionchanged event, since it will be fired once a date is chosen from the calendar.

check by calling the getPalDates function inside calendar's Visible monthchanged event  instead of month changed event

put a breakpoint in getPalDates to check at what times it is being called.

Author

Commented:
Hi dejaanbu,

Please forgive me, you lost me :(

Below is my Calendar Markup that shows I'm currently calling OnDayRender="MyCal_DayRender" OnVisibleMonthChanged="MyCal_MonthChange" OnSelectionChanged="MyCal_SelectionChanged"

CALENDAR MARKUP:

                                        <asp:Calendar ID="Calendar1" runat="server" BackColor="White"
                    BorderColor="#CCCCCC" BorderWidth="1px" Font-Names="Verdana" Font-Size="8pt"
                    ForeColor="#333333" Height="400px" Width="520px"
                    OnDayRender="MyCal_DayRender" OnVisibleMonthChanged="MyCal_MonthChange" OnSelectionChanged="MyCal_SelectionChanged" DayNameFormat="Shortest"
                    ShowGridLines="True">
                    <DayHeaderStyle Font-Bold="True" BackColor="#027ABB" ForeColor="White"
                        Height="30px" />
                    <NextPrevStyle Font-Size="9pt" ForeColor="#FFFFCC" />
                    <OtherMonthDayStyle ForeColor="#CC9966" />
                    <SelectedDayStyle BackColor="#CCCCFF" Font-Bold="True" />
                    <SelectorStyle BackColor="#FFCC66" />
                    <TitleStyle BackColor="#73BE1E"
                        Font-Bold="True" Font-Size="9pt" ForeColor="White" />
                    <TodayDayStyle BackColor="#CCCCCC" ForeColor="#333333" />
                </asp:Calendar>



CODEBEHIND:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ApplicationProcess_Secure_PhysicalActivityLog : System.Web.UI.Page
{
    string[,] palArr = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        hf_AppID.Value = Session["pi_id"].ToString();

        RetrieveCalendarNames();

        if (!IsPostBack)
        {
            getPalDates();
        }
    }

    //GET AVAILABLE DATE AND ITS CORRESPONDING NAME IN AN ARRAY
    protected void getPalDates()
    {
        int pi_id = Convert.ToInt32(Session["pi_id"]);

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessChoice"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "WellnessChoice_RetrieveDatesForCalendar";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        cmd.Parameters.AddWithValue("@pi_id", SqlDbType.Int).Value = pi_id;

        DataTable dtDates = new DataTable();

        SqlDataAdapter adp = new SqlDataAdapter();

        try
        {
            conn.Open();

            adp.SelectCommand = cmd;
            adp.Fill(dtDates);
            palArr = new string[13, 32];
            for (int iCnt = 0; iCnt <= dtDates.Rows.Count - 1; iCnt++)
            {
                Calendar1.SelectedDates.Add(Convert.ToDateTime(dtDates.Rows[0]["pal_date"]));
                DateTime dm = Convert.ToDateTime(dtDates.Rows[iCnt]["pal_date"]);
                palArr[dm.Month, dm.Day] = dtDates.Rows[iCnt]["palv_code"].ToString() + "|" + dtDates.Rows[iCnt]["palv_id"].ToString();
            }
        }

        catch (Exception ex)
        {
            ex.Message.ToString();
        }

        finally
        {
            conn.Close();
        }
    }

    //CUSTOMIZE UR CALENDAR RENDER EVENT NOW
    protected void MyCal_DayRender(object sender, DayRenderEventArgs e)
    {
        // remove if (!IsPostBack) if running into Render errors
        if (!IsPostBack)
        {
            CalendarDay day = (CalendarDay)e.Day;
            TableCell cell = (TableCell)e.Cell;

            // if (!day.IsOtherMonth)
            if (!day.IsOtherMonth && palArr[day.Date.Month, day.Date.Day] != null)
            {
                string palName = palArr[day.Date.Month, day.Date.Day];

                if (palName != null)
                {
                    var p = palName.Split('|');
                    if (p[1].ToString() == "2")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 255, 138, 215);
                    }
                    else if (p[1].ToString() == "3")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 255, 138, 140);
                    }
                    else if (p[1].ToString() == "4")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 255, 181, 138);
                    }
                    else if (p[1].ToString() == "5")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 255, 204, 138);
                    }
                    else if (p[1].ToString() == "6")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 255, 229, 138);
                    }
                    else if (p[1].ToString() == "7")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 255, 254, 138);
                    }
                    else if (p[1].ToString() == "8")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 221, 255, 138);
                    }
                    else if (p[1].ToString() == "9")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 146, 249, 134);
                    }
                    else if (p[1].ToString() == "10")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 138, 238, 255);
                    }
                    else if (p[1].ToString() == "11")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 136, 199, 252);
                    }
                    else if (p[1].ToString() == "12")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 133, 146, 246);
                    }
                    else if (p[1].ToString() == "13")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 195, 131, 242);
                    }

                    Label lbl = new Label();
                    lbl.Text = "<br>" + p[0];
                    e.Cell.Controls.Add(lbl);
                }
            }
        }
    }

    protected void MyCal_MonthChange(object sender, MonthChangedEventArgs e)
    {
        getPalDates();
    }

    protected void MyCal_SelectionChanged(object sender, EventArgs e)
    {
        calendarExt.Show();

        if (!IsPostBack)
        {
            RetrieveCalendarNames();
        }
    }

    protected void RetrieveCalendarNames()
    {
        if (!IsPostBack)
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessChoice"].ConnectionString);

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "WellnessChoice_TestTest";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;

            try
            {
                conn.Open();

                SqlDataReader rdr = cmd.ExecuteReader();

                ddl_Name.DataSource = rdr;
                ddl_Name.DataValueField = "palv_id";
                ddl_Name.DataTextField = "palv_names";
                ddl_Name.DataBind();

                rdr.Close();
            }

            catch (Exception ex)
            {
                ex.Message.ToString();
            }

            finally
            {
                conn.Close();
            }
        }
    }

    protected void btn_SavePhysicalActivityLog_Click(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessChoice"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "WellnessChoice_InsertPhysicalActivityLog";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        cmd.Parameters.AddWithValue("@pi_id", SqlDbType.Int).Value = hf_AppID.Value;
        cmd.Parameters.AddWithValue("@palv_id", SqlDbType.Int).Value = ddl_Name.SelectedItem.Value;
        cmd.Parameters.AddWithValue("@pal_date", SqlDbType.DateTime).Value = Calendar1.SelectedDate.ToShortDateString();
        //cmd.Parameters.AddWithValue("@pal_id", SqlDbType.Int).Value = hf_pal_id.Value;

        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
        }

        catch (Exception ex)
        {
            // ex.Message.ToString();
            lblSaveError.Text = ("Error on insert: " + ex.Message.ToString());
        }

        finally
        {
            Response.Redirect("PhysicalActivityLog.aspx");
            conn.Close();
        }
    }
}

Commented:
No Pbms....i didnt check ur code clearly..please embed ur code inside code tag. that is "
" "

Open in new window

". so that people can view ur code clearly.

the problem for the data not being displayed after postback is u have added if (!IsPostBack) condition in each method. there is no need for that.

remove if (!IsPostBack) block from all the methods EXCEPT PAGE LOAD event.
       
       

Author

Commented:
Hi dejaanbu,

The following code below allows me to view one entry per date on Page_Load. But if I where to select another month and then go back the dates disappear even when I refresh the page they are gone. I have to close the application and re open in order to see the dates again. If I where to remove IsPostBack except for Page_Load than other events start to malfunction :(

Also, is it possible to display multiple entries for a date? I have multiple entries for a single date but the calendar is only showing one entry instead of all entries for that date.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ApplicationProcess_Secure_PhysicalActivityLog : System.Web.UI.Page
{

    string[,] palArr = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        hf_AppID.Value = Session["pi_id"].ToString();

        RetrieveCalendarNames();

        if (!IsPostBack)
        {
            getPalDates();
        }
    }

    //GET AVAILABLE DATE AND ITS CORRESPONDING NAME IN AN ARRAY
    protected void getPalDates()
    {
        int pi_id = Convert.ToInt32(Session["pi_id"]);

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessChoice"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "WellnessChoice_RetrieveDatesForCalendar";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        cmd.Parameters.AddWithValue("@pi_id", SqlDbType.Int).Value = pi_id;

        DataTable dtDates = new DataTable();

        SqlDataAdapter adp = new SqlDataAdapter();

        try
        {
            conn.Open();

            adp.SelectCommand = cmd;
            adp.Fill(dtDates);
            palArr = new string[13, 32];
            for (int iCnt = 0; iCnt <= dtDates.Rows.Count - 1; iCnt++)
            {
                Calendar1.SelectedDates.Add(Convert.ToDateTime(dtDates.Rows[0]["pal_date"]));
                DateTime dm = Convert.ToDateTime(dtDates.Rows[iCnt]["pal_date"]);
                palArr[dm.Month, dm.Day] = dtDates.Rows[iCnt]["palv_code"].ToString() + "|" + dtDates.Rows[iCnt]["palv_id"].ToString();
            }
        }

        catch (Exception ex)
        {
            ex.Message.ToString();
        }

        finally
        {
            conn.Close();
        }
    }

    //CUSTOMIZE UR CALENDAR RENDER EVENT NOW
    protected void MyCal_DayRender(object sender, DayRenderEventArgs e)
    {
        // remove if (!IsPostBack) if running into Render errors
        if (!IsPostBack)
        {
            CalendarDay day = (CalendarDay)e.Day;
            TableCell cell = (TableCell)e.Cell;

            // if (!day.IsOtherMonth)
            if (!day.IsOtherMonth && palArr[day.Date.Month, day.Date.Day] != null)
            {
                string palName = palArr[day.Date.Month, day.Date.Day];

                if (palName != null)
                {
                    var p = palName.Split('|');
                    if (p[1].ToString() == "2")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 255, 138, 215);
                    }
                    else if (p[1].ToString() == "3")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 255, 138, 140);
                    }
                    else if (p[1].ToString() == "4")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 255, 181, 138);
                    }
                    else if (p[1].ToString() == "5")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 255, 204, 138);
                    }
                    else if (p[1].ToString() == "6")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 255, 229, 138);
                    }
                    else if (p[1].ToString() == "7")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 255, 254, 138);
                    }
                    else if (p[1].ToString() == "8")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 221, 255, 138);
                    }
                    else if (p[1].ToString() == "9")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 146, 249, 134);
                    }
                    else if (p[1].ToString() == "10")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 138, 238, 255);
                    }
                    else if (p[1].ToString() == "11")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 136, 199, 252);
                    }
                    else if (p[1].ToString() == "12")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 133, 146, 246);
                    }
                    else if (p[1].ToString() == "13")
                    {
                        e.Cell.BackColor = System.Drawing.Color.FromArgb(120, 195, 131, 242);
                    }

                    Label lbl = new Label();
                    lbl.Text = "<br>" + p[0];
                    e.Cell.Controls.Add(lbl);
                }
            }
        }
    }

    protected void MyCal_MonthChange(object sender, MonthChangedEventArgs e)
    {
        getPalDates();
    }

    protected void MyCal_SelectionChanged(object sender, EventArgs e)
    {
        calendarExt.Show();

        if (!IsPostBack)
        {
            RetrieveCalendarNames();
        }
    }

    protected void RetrieveCalendarNames()
    {
        if (!IsPostBack)
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessChoice"].ConnectionString);

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "WellnessChoice_TestTest";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = conn;

            try
            {
                conn.Open();

                SqlDataReader rdr = cmd.ExecuteReader();

                ddl_Name.DataSource = rdr;
                ddl_Name.DataValueField = "palv_id";
                ddl_Name.DataTextField = "palv_names";
                ddl_Name.DataBind();

                rdr.Close();
            }

            catch (Exception ex)
            {
                ex.Message.ToString();
            }

            finally
            {
                conn.Close();
            }
        }
    }

    protected void btn_SavePhysicalActivityLog_Click(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["WellnessChoice"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "WellnessChoice_InsertPhysicalActivityLog";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        cmd.Parameters.AddWithValue("@pi_id", SqlDbType.Int).Value = hf_AppID.Value;
        cmd.Parameters.AddWithValue("@palv_id", SqlDbType.Int).Value = ddl_Name.SelectedItem.Value;
        cmd.Parameters.AddWithValue("@pal_date", SqlDbType.DateTime).Value = Calendar1.SelectedDate.ToShortDateString();
        //cmd.Parameters.AddWithValue("@pal_id", SqlDbType.Int).Value = hf_pal_id.Value;

        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
        }

        catch (Exception ex)
        {
            // ex.Message.ToString();
            lblSaveError.Text = ("Error on insert: " + ex.Message.ToString());
        }

        finally
        {
            Response.Redirect("PhysicalActivityLog.aspx");
            conn.Close();
        }
    }
}

Open in new window

Commented:
what error u get, when u didnt add postback condition in other methods. I have given my suggestion to use Linq query. other experts may come up with better solution in your new question posted.

Author

Commented:
Thanks for helping I was able to figure out the issue elsewhere.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial