c # - «Введенная строка не была в правильном формате» в моей форме Windows, когда я пытаюсь вычислить значения - PullRequest
0 голосов
/ 11 октября 2018

В моей форме я пытаюсь получить результаты, в которых данные, введенные в текстовые поля, добавляются и отображаются в ярлыке под ними.Когда я отлаживаю форму и нажимаю на кнопки, они всегда возвращают мне ответ «строка ввода не была в правильном формате».С чем можно повозиться в коде, чтобы исправить эту ошибку?

namespace practice_calculation
{
    public partial class Calculation : Form
    {
        //setting variables for input 
         Int32 int1 = 0;
         Int32 int2 = 0;
         Int32 intSum = 0;
         decimal dec1 = 0m;
         decimal dec2 = 0m;
         decimal decSum = 0m;
         double dbl1 = 0;
         double dbl2 = 0;
         double dblSum = 0;

        public Calculation()
        {
            InitializeComponent();
        }

        private void integer_Calculate_Button_Click(object sender, EventArgs e)
        {           
            try
            {
                Int32 int1; // to hold integer 1 value
                Int32 int2; // to hold integer 2 value
                Int32 intSum; // to hold the sum of int1 and int2

                // Get the values
                int1 = Int32.Parse(int1_Masked_Text_Box.Text);
                int2 = Int32.Parse(int2_Masked_Text_Box.Text);
                intSum = Int32.Parse(int_Results_Label.Text);

                // Calculate the Sum
                intSum = (int1 + int2);

                // Display the Sum
                int_Results_Label.Text = intSum.ToString("n1");
            }
            catch (Exception ex)
            {
                // Display the error message.
                MessageBox.Show(ex.Message);
            }
        }

        private void exitButton_Click(object sender, EventArgs e)
        {
            //close form
            this.Close();
        }

        private void dec_Calculate_Button_Click(object sender, EventArgs e)
        {
            try
            {
                Decimal dec1;  // to hold decimal 1 value
                Decimal dec2;  // to hold decimal 2 value
                Decimal decSum;  // to hold sum of dec1 and dec2

                // Get the values
                dec1 = Decimal.Parse(dec1_Masked_Text_Box.Text);
                dec2 = Decimal.Parse(dec2_Masked_Text_Box.Text);
                decSum = Decimal.Parse(dec_Results_Label.Text);

                // Calculate the Sum
                decSum = (dec1 + dec2);

                //Display the Sum
                dec_Results_Label.Text = decSum.ToString("n1");
            }
            catch (Exception ex)
            {
                // Display the error message.
                MessageBox.Show(ex.Message);
            }
        }

        private void dbl_Calculate_Buttons_Click(object sender, EventArgs e)
        {
            try
            {
                Double dbl1; // to hold double 1 value
                Double dbl2; // to hold double 2 value
                Double dblSum; // to hold sum of dbl1 and dbl2

                // Get the values
                dbl1 = Double.Parse(dbl1_Masked_Text_Box.Text);
                dbl2 = Double.Parse(dbl2_Masked_Text_Box.Text);
                dblSum = Double.Parse(dbl_Results_Label.Text);

                // Calculate the Sum
                dblSum = (dbl1 + dbl2);

                //Display the Sum
                dbl_Results_Label.Text = decSum.ToString("n1");
            }
            catch (Exception ex)
            {
                // Display the error message.
                MessageBox.Show(ex.Message);
            }
        }
    }
}

1 Ответ

0 голосов
/ 11 октября 2018

Возможно ошибка вашего кода есть в метке, вы должны преобразовать результат после его расчета.Если текст на вашем ярлыке не является целым числом.Вот почему он выдавал ошибку входная строка была не в правильном формате .Если ваша метка пуста или имеет значение null, которое не может быть проанализировано как int.

Попробуйте это.

        Int32 int1;
        Int32 int2;
        Int32 intsum;

        int1 = Int32.Parse(textBox1.Text);
        int2 = Int32.Parse(textBox2.Text);
        //intsum = Int32.Parse(label1.Text);

        intsum = int1 + int2;

        label1.Text = intsum.ToString("n1");
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...