joe_pool_is Posted February 2, 2009 Posted February 2, 2009 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? Quote Avoid Sears Home Improvement
Administrators PlausiblyDamp Posted February 2, 2009 Administrators Posted February 2, 2009 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. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
joe_pool_is Posted February 2, 2009 Author Posted February 2, 2009 That helped a lot! Thank you. Quote Avoid Sears Home Improvement
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.