Introduction
A common task is to have a calendar control pop-up when the user picks a button / image button. There are plenty of third party solutions which can achieve this. This post describes how to achive this the quick and dirty way:
- Repetitive code
- No JavaScript
- No user controls
Implementation
To implement the calendar pop-up, we need three controls:
- A text box
- A button / image button
- A calendar control
Create a table
or div
and place the three controls inside a table cell or the div
. Make sure to set the visible attribute in the calendar control to false
in the designer or in the page_load
event.
Then create the event handler for the button:
protected void btnDate_Click1(object sender, EventArgs e) {
DateTime date = new DateTime();
this.cal1.Visible = !(this.cal1.Visible);
if (this.cal1.Visible) {
if (DateTime.TryParse(txtDate.Text,out date)){
cal1.SelectedDate = date;
}
this.cal1.Attributes.Add("style","POSITION: absolute");
}
}
The above code is really straightforward. The button is used to show or hide the calendar control. Also, if the date from the textbox is a valid date, it will be passed to the calendar control. The nice part comes at the end by setting the "POSITION: absolute
" CSS attribute we achieve the floating effect of the calendar, instead of having the control push down all the controls below it.
Finally we must handle the SelectionChanged
event in the calendar control to set the date value in the textbox. This is done by converting the date
into a string
and extracting the first 10 characters. Also, we must hide the calendar once the date has been picked.
protected void cal1_SelectionChanged(object sender, EventArgs e) {
txtDate.Text = this.cal1.SelectedDate.ToString().Substring(0,10);
this.cal1.Visible = false;
}
The following snippet can be used to generate the above code quickly it is only necesary to enter the name of the textbox, button and calendar controls, and of course, bind it to the appropiate events.
="1.0"="utf-8"
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>calPopUp</Title>
<Shortcut>calPopUp</Shortcut>
<Description>Calendar PopUp via button</Description>
<Author>Armando de la Torre</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>calendar</ID>
<ToolTip>calendar control</ToolTip>
<Default>cal</Default>
</Literal>
<Literal>
<ID>button</ID>
<ToolTip>Button control</ToolTip>
<Default>btnDate</Default>
</Literal>
<Literal>
<ID>text</ID>
<ToolTip>Text Control</ToolTip>
<Default>txtDate</Default>
</Literal>
</Declarations>
<Code Language="csharp">
<![CDATA[
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>