mercredi 22 avril 2020

C# - Can't get if statement to work as it should - Throw new system.ArgumentException

I am new to learning C#, and i'm attempting to create a WPF application that asks the user questions. I then convert those answers into strings and export them to a CSV file.

One of the questions is "Pick a number between 1-5". I need to make this so that if a number is less than 1, or more than 5, it asks the user to pick a different number. I tried to achieve this by using the below code. It somewhat works because when i click save as, nothing will happen if i use a wrong number. But it doesn't ask the user like i want it to. Please could someone take a look at my code and let me know why this isn't working?

        private void btnSaveClick(object sender, RoutedEventArgs e)
        {
            try
            {
                string firstName = tbFirstName.Text;
                string lastName = tbLastName.Text;
                string jobTitle = tbJobTitle.Text;
                string chickenEgg = tbChickenEgg.Text;
                string _oneFive = tbNumber.Text;
                int oneFive = Convert.ToInt32(_oneFive);

                if ((oneFive > 5) || (oneFive < 1))
                {
                    throw new System.ArgumentException("Please use a number between 1-5");
                }

                string csvContent = string.Format("{0},{1},{2},{3},{4}", FormatCSV(firstName), FormatCSV(lastName), FormatCSV(jobTitle), FormatCSV(chickenEgg), FormatCSV(_oneFive));

                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "CSV file (*.csv)|*.csv";
                if (saveFileDialog.ShowDialog() == true)
                    File.WriteAllText(saveFileDialog.FileName, csvContent);

                tbFirstName.Clear();
                tbLastName.Clear();
                tbJobTitle.Clear();
                tbChickenEgg.Clear();
                tbNumber.Clear();

                tbFirstName.Focus();
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
        }

        static string FormatCSV(string _input)
        {

            try
            {
                string result = "";

                if ((_input.Contains(",")) || (_input.Contains(" ")))
                {
                    result = string.Format("\"{0}\"", _input.Trim());
                }
                else
                {
                    result = _input.Trim();
                }


                return result;
            }
            catch (Exception e)
            {
                throw e;
            }

When i get to the catch block, nothing displays or seems to happen.

Thank you in advance!

Aucun commentaire:

Enregistrer un commentaire