0

I am trying to validate my WPF programme in C# to check that the user has inputted a date into my DatePicker event. If the user has not input the date I would like it to let the user re input the data before running the whole programme again. I would also like it to do the same if the user has input a numer of less that 1 or more than 10. However at the moment it simply continues on with the rest of the programme causing it to break later on.

My 'textbox' event is called UserInput and my DatePicker is called 'RequestedDate'

My code:

if (int.TryParse(UserInput.Text, out numberEntered))
{

    while (DateRequested.SelectedDate == null)
    {
        MessageBox.Show("You have not input a valid date");
        Output.Text = "Please try again";

    }

       while (numberEntered < 1 || numberEntered > 10)
    {
        MessageBox.Show("You can only book tickets with values more than one or less than 10");
        Output.Text = "Please try again";
        break;
    }

    Output.Text = "Number of tickets selected: " + UserInput.Text + "Date: " + DateRequested.Text;
}
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
  • 4
    You shouldn't use a loop. Just verify with `if...` blocks or similar statements and prompt the user when something is not right. Have them click the submit button again and verify from the start... – John Willemse Feb 19 '13 at 20:29
  • 2
    You should do it the wpf way and set Validation rules. The way your code is, you might as well be using winforms. – TYY Feb 19 '13 at 20:32
  • You appear to be missing a break inside your first while-loop-that should-be-an-if-statement. – Chris Kerekes Feb 19 '13 at 20:36
  • Note just in case you are unsure of how to use ValidationRules, check out the example on MSDN http://msdn.microsoft.com/en-us/library/system.windows.data.binding.validationrules.aspx – TYY Feb 19 '13 at 20:40

2 Answers2

0

You have several issues here:

1 - UI Elements are not 'events', therefore there's no such thing as a TextBox Event.

2 - UI is not Data. Therefore you should abstract your logic in a ViewModel and operate against that.

Post your XAML and I will edit my answer showing the proper way to implement this.

Community
  • 1
  • 1
Federico Berasategui
  • 43,562
  • 11
  • 100
  • 154
0

You should just bind your TextBox.Text to a DateTime object, this will give the user feedback if the data entered is incorrect by adding a red border around the TextBox.

If the DateTime is mandatory you should setup a ValidationRule for your TextBox to validate, there is no need to drag all this UI logic into your Model.

sa_ddam213
  • 42,848
  • 7
  • 101
  • 110