Introduction
Hello! Today, I am going to explain how to use Calendar Control as DateTime Picker in ASP.Net. I know there are various third party controls, in which you can get ready made DTP Controls easily. But here, we will see how we can develop our own DTP Control using ASP.Net.
So, let’s start the coding steps. Right!!
Step 1: Since we are going to use Calendar Control, we need to put the Control in our ASP.Net HTML script.
In the above image, you can see that we have three controls - Calendar, TextBox, and LinkButton.
Now, we will do some customization in the code, to maintain the Control behaviour.
Step 2: Now, we have the Calendar Control set to visible = false, by default.
So, we will make it visible = true on the LinkButton click event, so the user can see the Calendar on link click.
- protected void lnkpickdate_Click(object sender, EventArgs e) {
- datepicker.Visible = true;
- }
Step 3: OK. Now, we need to get the Calendar Control selected value into TextBox.
So, we will write the code for this, on datepicker_SelectionChanged event. You can see in the following image also .
- protected void datepicker_SelectionChanged(object sender, EventArgs e) {
- txtdtp.Text = datepicker.SelectedDate.ToLongDateString();
- datepicker.Visible = false;
- }
Now, we have got the selected date into TextBox and it should work fine, as expected. You can see in the image, shown below.
Step 4: Now, you can see that we are getting the date but not in an attractive format. To make it attractive, we need to go some extra steps ahead. We can do the formatting of the Control.
All right. Now, we get it looking better than the previous one. But, you can see, we are getting the Date Time value in a format like Tuesday, July 12, 2016. Here, I want to get it in dd/mm/yyyy format. For this, we will write the following code:
- protected void datepicker_SelectionChanged(object sender, EventArgs e) {
- txtdtp.Text = datepicker.SelectedDate.ToShortDateString();
- datepicker.Visible = false;
- }
Now, we are all set. We can see the expected output of DateTime Control.
I hope this tutorial would be useful for you guys. Your comments and feedback would be appreciated.