Как использовать try / catch для проверки правильности ввода данных в несколько текстовых полей в форме.И прекратить ввод данных после возникновения ошибки - PullRequest
0 голосов
/ 28 октября 2018

Я пытаюсь создать простое окно для универа, в котором записывается информация о клиенте в списке (во время работы программы).Введенные данные, такие как имя и номер телефона.Я могу заставить людей добавить в список и найти их или удалить их.Но одна из сложных задач, которые мне нужно сделать, это использовать try / catch для проверки ввода данных, введенных в текстовые поля.

Я уже искал в сети, чтобы попытаться найти решение, и не смогнайди все, что соответствует тому, что я пытаюсь сделать.Я также обнаружил, что использование этого метода не лучший способ сделать это.Я действительно могу заставить программу легко проверять данные, используя операторы if.но это не дает мне оценки, делая это таким образом.

Мне также удалось получить попытку / поймать, чтобы обнаружить ошибку ввода алфавитных символов в телефонное поле моей формы, но затем он продолжаетк следующему коду после попытки / уловки и вводу нового пользователя с номером телефона в любом случае (он не должен вводить какие-либо данные в систему после обнаружения ошибки).

Как я могуостановить код после продолжения попытки в методе кнопки?и есть ли более простой способ поставить отдельную попытку / уловку для каждого текстового поля?

Вот так выглядит мое окно:

enter image description here

Вот класс для кода моих кнопок:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using BusinessObjects;

namespace Demo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        //Object to hold details for each customer.
        Customer cust = new Customer();
        //List to hold details of each customer.
        private MailingList store = new MailingList();
        //Variable to set starting ID number.
        private int ID = 10001;

        public MainWindow()
        {
            InitializeComponent();
        }

        //Button for Adding a customer with a specific assigned ID number.
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
                /*if (txtTelephone.Text.Length > 11)
                {


                }
                else if (txtFName.Text.Length > 5)
                {

                }*/
                //Stores the details of the textboxes into the customer details for each list entry.
                cust.ID = ID;
                cust.FirstName = txtFName.Text;
                cust.SecondName = txtSName.Text;
                cust.Email = txtEmail.Text;
                cust.SkypeID = txtSkype.Text;
            try
            {
                cust.Telephone = Convert.ToInt32(txtTelephone.Text);
            }
            catch
            {
                MessageBox.Show("Please enter an 11 digit phone number");
                txtTelephone.Clear();
            }
                cust.PrefContact = txtPrefContact.Text;

                //Adds the details of the person above to the list and increases the ID number by one for the next entry.
                store.add(cust);
                ID++;

                //Shows user the details of the person added to the list.
                MessageBox.Show("Name: " + cust.FirstName + " " + cust.SecondName +
                    "\nEmail: " + cust.Email +
                    "\nSkype: " + cust.SkypeID +
                    "\nTelephone: " + cust.Telephone +
                    "\nPreferred Contact: " + cust.PrefContact +
                    "\n " + cust.ID);

                //Clears all textboxes for next entry after adding a customer.
                txtFName.Clear();
                txtSName.Clear();
                txtEmail.Clear();
                txtSkype.Clear();
                txtTelephone.Clear();
                txtPrefContact.Clear();
        }

        //Button for deleting a specific customer with their specific ID.
        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            int id = Int32.Parse(txtID.Text);
            store.delete(id);
        }

        //Button for Finding a specific customer with their specific ID.
        private void btnFind_Click(object sender, RoutedEventArgs e)
        {
            //Allows the text in the ID textbox to be changed to an int to be used for checking the ID.
            int id = Int32.Parse(txtID.Text);

            //Searchs to see if this ID exists, and returns NULL if not.
            store.find(cust.ID);


            /*If the ID number entered is not found in the list, 
            an error message is displayed to say the user does not exist.
            If the ID does exist, shows the user the details of the person with that ID. */
            if (store.find(id) == null)
            {
                //Displays error message to tell user that this customer does not exist.
                MessageBox.Show("Invalid ID!" +
                                "\nNo Customer with this ID exist!");
            }
            else
            {
                //Displays the details of customer with specific ID.
                MessageBox.Show(cust.Display(cust.ID));
            }
        }      
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...