Wednesday, April 11, 2012

DateTime Picker Control in C# (Windows Forms)

Author : Prakash Pradeep Gopu
The DateTimePicker control allows you to display and collect date and time from the user with a specified format.
The DateTimePicker control has two parts, a label that displays the selected date and a popup calendar that allows users to select a new date. The most important property of the DateTimePicker is the Value property, which holds the selected date and time.
dateTimePicker1.Value = DateTime.Today;
The Value property contains the current date and time the control is set to. You can use the Text property or the appropriate member of Value to get the date and time value.
  DateTime iDate;
  iDate = dateTimePicker1.Value;
The control can display one of several styles, depending on its property values. The values can be displayed in four formats, which are set by the Format property: Long, Short, Time, or Custom.
  dateTimePicker1.Format = DateTimePickerFormat.Short;
The following C# program shows how to set and get the value of a DateTimePicker1 control.

1)Create  form in the windows application
2)Drag the Date Time picker control on to your form and place button on to the same form.
3)Under the page_Load event of formAm seting the current date and  Under the button click am reading selected Date value .Simply copy and paste the following code in page_load() and Button1_Click () events.
 


private void button1_Click(object sender, EventArgs e)
        {
            DateTime iDate;
           
            iDate = dateTimePicker1.Value;

            MessageBox.Show("Selected date is " + iDate);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            dateTimePicker1.Format = DateTimePickerFormat.Short;
            dateTimePicker1.Value = DateTime.Today;
        }

Output :

1 comment: