Write your own Date Editor ASP.NET server control
Visual Studio .Net comes with a lot of useful ASP.NET server controls, such
as Label, TextBox, Button, etc. However, I always wanted something they don't
have-a Date Editor control, which lets you input or pick a date. So I set out to
write my own DateEditor server control.
Here is what it should look like on a web form. It has two modes: Display and Edit modes.
It will need to expose just one property: date, which represents the DateTime value the control is encapsulating. To make things easier to understand, I make this DateEditor control a composite control, instead of a rendered control, because as you can see it has quite a few controls when it is shown and they are all normal .Net server controls, such as TextBox, Button, and Label.
Since we want to inherit the basic functionalities of a web control, we will derive this control from WebControl class in the System.Web.UI.WebControls namespace. The most important methods are the CreateChildControls and Render method. In the CreateChildControl method, we instantiate and initialize all the child controls, then wire them up to their respective event handlers. It is in the Render method that we spell out the controls on HtmlTextWriter object which encapsulates the network output stream we are writing to.
Here is the two methods, complete code can be downloaded by clicking the "Launch now" button above.
private Label lbl_Date;
private Button btn_Edit;
private TextBox txt_Day, txt_Month, txt_Year;
private Button btn_OK, btn_Cancel;
protected override void CreateChildControls()
Controls.Clear(); lbl_Date = new Label();
lbl_Date.Text = date.ToShortDateString();
btn_Edit = new Button();
btn_Edit.Text = "Edit";
btn_Edit.Click += new EventHandler(this.btn_Edit_Click);
txt_Month = new TextBox();
txt_Day = new TextBox();
txt_Day.Width = Unit.Point(30);
txt_Year = new TextBox();
btn_OK = new Button();
btn_OK.Text = "OK";
btn_OK.Click += new EventHandler(this.btn_OK_Click);
btn_Cancel = new Button();
btn_Cancel.Text = "Cancel";
btn_Cancel.Click += new EventHandler(this.btn_Cancel_Click);
calendar = new Calendar();
calendar.SelectionChanged += new EventHandler(this.Calendar_SelectionChanged);
protected override void Render(HtmlTextWriter writer)
It is quite easy to add a calendar so that you can pick the date instead of inputting them yourself, but I will leave this task for you to figure out.