I decided to write this example because I always encounter this kind of question at http://forums.asp.net/.
This example basically changes the background color of the calendar dates based on the event dates from the database. You can tweak the codes provided in this example to suit your needs.
Here are the code blocks below:
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
DataTable dt = GetDates();
DateTime eventDate;
string eventType = string.Empty;
if (dt.Rows.Count > 0){
for (int i = 0; i < dt.Rows.Count; i++){
//Where ColumnFieldForDate and ColumnFieldForEventType are the field names from your database
eventDate = Convert.ToDateTime(dt.Rows[i]["ColumnFieldForDate"]);
eventType = dt.Rows[i]["ColumnFieldForEventType"].ToString();
if (e.Day.Date == eventDate)
{
if (eventType == "Meeting")
{
e.Cell.BackColor = System.Drawing.Color.Blue;
}
else if (eventType == "Holiday")
{
e.Cell.BackColor = System.Drawing.Color.Red;
}
else
{
e.Cell.BackColor = System.Drawing.Color.Yellow;
}
}
}
}
}
public DataTable GetDates()
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING HERE");
try
{
connection.Open();
SqlCommand sqlCmd = new SqlCommand("SELECT * FROM TableName", connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
return dt;
}
As you can see the code above is very straight forward and self explanatory.That's it!
Technorati Tags:
ASP.NET,
C#,
TipsTricks