Add Text To Day Cell In Calendar Control In C#

This code snippet shows how to add text to the day cell in a Calendar control. It uses the OnDayRender event to add text to a day cell from a DataTable object.
  1. //Default.aspx
  2.  
  3. <form id="form1" runat="server">
  4.         <div>
  5.                 <asp:Calendar ID="Calendar" runat="server" OnDayRender="DayRender" ShowGridLines="true" />
  6.         </div>
  7. </form>
  8.  
  9. //Default.aspx.cs
  10.  
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Data;
  14. using System.Web;
  15. using System.Web.UI;
  16. using System.Web.UI.WebControls;
  17.  
  18. public partial class _Default : System.Web.UI.Page
  19. {
  20.     DataTable _DayEventsTable;
  21.  
  22.     protected void Page_Load(object sender, EventArgs e)
  23.     {
  24.         _DayEventsTable = new DataTable();
  25.         _DayEventsTable.Columns.Add("Date");
  26.         _DayEventsTable.Columns.Add("Title");
  27.  
  28.         _DayEventsTable.Rows.Add(DateTime.Now.AddDays(-2).Date.ToString(), "Meeting with Boss");
  29.         _DayEventsTable.Rows.Add(DateTime.Now.Date.ToString(), "Lunch with Suzan");
  30.         _DayEventsTable.Rows.Add(DateTime.Now.AddDays(2).Date.ToString(), "Trip to Paris!");
  31.     }
  32.  
  33.     protected void DayRender(object sender, DayRenderEventArgs e)
  34.     {
  35.         foreach (DataRow Row in _DayEventsTable.Rows)
  36.         {
  37.             string Date = Row["Date"].ToString();
  38.             string Title = Row["Title"].ToString();
  39.  
  40.             if (Date == e.Day.Date.ToString())
  41.             {
  42.                 e.Cell.Controls.Add(new LiteralControl("<p>" + Title + "</p>"));
  43.             }
  44.         }
  45.     }
  46. }

No comments:

Post a Comment