Introduction:
We all are familiar with the ASP.NET Calendar
control. We can click on dates and it will be highlighted. But once you refresh the page, the selected dates are gone. How about making a small application that remembers the date you selected.
Creating a Simple Calendar:
For creating a calendar, simply drag and drop the Calendar
control from the ToolBox usually located on the left in VS.NET IDE. Once you get the Calendar
control on the page, you can change the appearance of the calendar by right clicking on it and choosing Properties, and then Auto Format. The image below shows just a calendar highlighting current date.
Making Database Table for storing selected Dates:
In this example, we also need to create a database. I made the database in SQL Server 2000. To keep this simple, I only made two fields: one is CalendarID
which is an autogenerating number and the other is DateTime
.
Page_Load Event Code:
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
BindData();
}
}
BindData Method Code:
public void BindData()
{
SqlCommand myCommand = new SqlCommand("SELECT CalDate FROM tblCal",
myConnection);
myCommand.CommandType = CommandType.Text;
myConnection.Open();
SqlDataReader dr = myCommand.ExecuteReader();
while( dr.Read() == true )
{
myCal.SelectedDates.Add((DateTime)dr.GetSqlDateTime(0));
}
dr.Close();
myConnection.Close();
}
Mark Test Dates Button Event Code:
private void Button1_Click(object sender, System.EventArgs e)
{
BindData();
myCal.SelectedDayStyle.BackColor = System.Drawing.Color.Red;
SqlCommand myCommand = new SqlCommand("InsertDate",myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add(new SqlParameter("@v_DateTime",SqlDbType.DateTime));
myCommand.Parameters["@v_DateTime"].Value = selectedDate;
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}
Once you press the button, your calendar will appear like the image below showing the selected dates:
Loading the page a second time:
You can also change the color when the page loads a second time as seen in the image below in which the calendar is loaded a second time:
Thanks and enjoy coding!