Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

I have a Windows VS2005 Form where my Clients can select a Start Date and an End Date.

 

Obviously, the Start Date must occur before the End Date, or there will be problems, so I need to validate the entries.

 

Where should I validate these controls, and how should this be done?

 

I have existing code that validates the control and give the Client a friendly message box when it is incorrect when the DateTimePickerControl's ValueChanged event is fired:

void DateTime_ValueChanged(object sender, EventArgs e) {
 if (sender is DateTimePicker) {
   if (dtEnd.Value < dtStart.Value) {
     string strCtrl = string.Empty;
     if (sender.Equals(dtStart) == true) {
       strCtrl = lblStartDate.Text;
       DateTime newVal = dtStart.Value.AddDays(-1);
       while (dtEnd.Value < newVal) {
         newVal = newVal.AddDays(-1);
       }
       dtStart.Value = newVal;
       dtStart.Focus();
     } else if (sender.Equals(dtEnd) == true) {
       strCtrl = lblEndDate.Text;
       DateTime newVal = dtEnd.Value.AddDays(1);
       while (newVal < dtStart.Value) {
         newVal = newVal.AddDays(1);
       }
       dtEnd.Value = newVal;
       dtEnd.Focus();
     }
     string fmt = string.Format("{0} must be less than or equal to {1}.\r\n\r\nYour {2} has been modified.",
                                 lblStartDate.Text, lblEndDate.Text, strCtrl);
     MessageBox.Show(fmt, "Invalid Date", MessageBoxButtons.OK, MessageBoxIcon.Information, 0);
   }
 }
}

 

If someone drops the Calendar down and tries to scroll to a month or year that is out of range, the GUI goes nuts with message boxes from my code until the system runs out of memory.

 

I tried rewriting the code to only respond when the calendar scrolls back up, but then validation would fail whenever a date was manually entered in the textbox.

 

How should I address this?

  • Administrators
Posted

If you use the Validating Event rather than the ValueChanged event it should prevent the problem with the event triggering itself repeatedly.

 

Also you might consider an ErrorProvider rather than a MessageBox as a less intrusive way of notifying the user.

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...