how to spin the date (a new control in C#)

G

Guest

I have VS 2005 (C#)
There is a control numericUpDown so you can spin numeric values. What I need
to do is to spin date (+- one day). How to do that? Moreover, I want a user
to type the date as well. So the control should validate the typed values on
the fly. Is it possible?
 
S

Simon Tamman

Yes.
Create a UserControl and add a datetimepicker and a button above and below.
Hook up the buttons to an event and in the event set the "Value" property of
the datetimepicker to the current Value.AddDay(1) or Value.AddDay(-1)
depending on if the button will make the date go up or down.
If you specify that the format used in the datetimepicker is "Custom" then
you can specify a CustomFormat string, like "MM/dd/yy" for US time. The user
will be able to type into this control although they will have to use the
arrow keys to change which part of the date they are editing. A hidden
benefit is that they can also use the Arrow Up and Down keys to move the
selected part of the date "up" or "down".
The datetimepicker also has inbuilt validation.
 
G

Guest

Is there a different way? I did it this way (but unfortunatelly without
letting user type the date). I put textbox (read only) and numericupdown
control. It works ok.
But how to validate (during typing) values typed (by a user) into the textbox?
 
S

Simon Tamman

Well I only pressed the datetimepicker to avoid having to write your own
logic for the textbox as that's more cumbersome.

If you hook up to the KeyPress or KeyUp event on the textbox you'll be able
to perform the validation during typing but remaining logic will be rather
complicated (e.g. to work out via the location of the focus and which part
of the date they're writing and then validate their input) .

What would be easier is to use the TextBox Enter and Leave events to
validate the date once they've finishing typing it. You could then validate
the date by calling DateTime.TryParse(). If the date is invalid put the
original value back into the textbox.

Failing that you could search on Google for such a control, perhaps someone
has already done all the work for you?

If you do end up writing the logic for the validation of the date in the
textbox.KeyPress or KeyUp event be sure to use DateTime.IsLeapYear for your
leap year validation.

HTH

Simon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top