Ryder217
Ryder217

Reputation: 1

What error messaging do i add to my windows forms C# program?

My program is a prime numbers C# program and I need error messaging that shows what happens when I add letters and/or larger numbers first in the textboxes. Here is my code:

namespace Task_2_Prime_Numbers
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btcalculate_Click(object sender, EventArgs e)
        {
            // Find all Prime numbers between the first and last prime numbers
            int firstnum = Convert.ToInt32(number1.Text);
            int lastnum = Convert.ToInt32(number2.Text);

            IbPrime.Items.Clear();

            // See which numbers are factors and add them to the list box
            for (int i = firstnum; i <= lastnum; i++)
            {
                if (IsPrime(i))
                {
                    IbPrime.Items.Add(i);
                }

            }
        }
        private bool IsPrime(int num)
        {
            if (num < 2)
                return false;
            // Looks for a number that evenly divides the sum
            for (int i = 2; i <= num / 2; i++)
                if (num % i == 0)
                    return false;

            return true;
        }
    }
}

Upvotes: 0

Views: 54

Answers (1)

Paul S&#252;tterlin
Paul S&#252;tterlin

Reputation: 334

Use int.TryParse.

int firstnum, lastnum;
if (!int.TryParse(number1.Text, out firstnum)){
    // Error
}
if (!int.TryParse(number2.Text, out lastnum)){
    // Error
}
if (firstnum >= lastnum){
    // Error
}

Upvotes: 1

Related Questions