views:

245

answers:

3

I have a c# .net project and want an input text box for a date value. I want it to display a default value of mm/dd/yyyy and then allow users to enter valid dates.

I have tried using a masked text box but it doesn't like having the above format.

If i try and use //__ looks naff and so does 00/00/0000 and of course if you put in '0' like 03/11/2009 you get 3/11/29 because the 0's are deleted as part of the mask.

What is the best way to set up an input box like this, effectively with a mask, only allowing numbers, and validation (though at this point I am not so worried about that).

This seems so simple and isn't.

+1  A: 

Try examining the the date in the OnChange event. Check the length of the text, adding / when appropriate.

Alternatively, see if the the DatePicker may be a better choice...

Michael Rodrigues
A: 

Why not try and use a plugin like the jQuery UI DatePicker?

http://docs.jquery.com/UI/Datepicker

They are lightweight, tested and saves work!

Rajeshwaran S P
A: 

Assuming Windows Forms, the DateTimePicker is the tool for the job.

Here is an example with the MaskedTextBox, but since you say it doesn't work...

Another good try, if you're using DataBinding, if by instantiating a Binding (Binding for WPF) class and handling its Parse and Format events (these don't seem to exist in WPF, but there must be some way).

In short:

Binding b = new Binding("Text", BindingSourceInstance, "data.DateCreated");
b.Parse += new EventHandler(b_Parse);
b.Format += new EventHandler(b_Format);

private void b_Format(object sender, ConvertEventArgs e) {
    if (e.DesiredType != typeof(DateTime)) return;

    e.Value.ToString("dd/MM/yyyy");
    // Or you may prefer some other variants:
    // e.Value.ToShortDateString();
    // e.Value.ToLongDateString();
    // e.Value.ToString("dd/MM/yyyy", CultureInfo.CurrentCulture.DateTimeInfo.ShortDatePattern);
}

private void b_Parse(object sender, ConvertEventArgs e) {
    // Choose whether you to handle perhaps bad input formats...

    e.Value = DateTime.Parse(e.Value, CultureInfo.InvariantCulture); // The CultureInfo here may be whatever you choose.
}
Will Marcouiller