Windows Forms C # «Неправильный формат входной строки» - PullRequest
1 голос
/ 08 ноября 2010

У меня есть простое приложение Windows Forms, которое используется для вычисления решений квадратного уравнения.Поскольку для этого необходимо ввести некоторые значения в три разных текстовых поля, а затем, нажав кнопку «Рассчитать», выполнить некоторые вычисления с введенными значениями.После тестирования приложения и нажатия кнопки «Рассчитать» перед вводом любых значений я получаю Input string was not in a correct format Это связано с попыткой проанализировать несуществующее значение.Есть ли способ избежать этого?Я пытался создать условное условие, основанное на том, была ли нажата кнопка, и в текстовых полях не было значений, чтобы ничего не делать, но это не совсем работало.Вот мой код конструктора:

namespace QuadraticSolver
{
    partial class QuadraticSolver
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.lblPrompt = new System.Windows.Forms.Label();
            this.lblA = new System.Windows.Forms.Label();
            this.lblB = new System.Windows.Forms.Label();
            this.lblC = new System.Windows.Forms.Label();
            this.txtA = new System.Windows.Forms.TextBox();
            this.txtB = new System.Windows.Forms.TextBox();
            this.txtC = new System.Windows.Forms.TextBox();
            this.btnCalculate = new System.Windows.Forms.Button();
            this.lblSolutions = new System.Windows.Forms.Label();
            this.txtSolution1 = new System.Windows.Forms.TextBox();
            this.txtSolution2 = new System.Windows.Forms.TextBox();
            this.chkImaginary = new System.Windows.Forms.CheckBox();
            this.SuspendLayout();
            // 
            // lblPrompt
            // 
            this.lblPrompt.AutoSize = true;
            this.lblPrompt.Location = new System.Drawing.Point(12, 9);
            this.lblPrompt.Name = "lblPrompt";
            this.lblPrompt.Size = new System.Drawing.Size(92, 13);
            this.lblPrompt.TabIndex = 0;
            this.lblPrompt.Text = "Enter Your Values";
            // 
            // lblA
            // 
            this.lblA.AutoSize = true;
            this.lblA.Location = new System.Drawing.Point(12, 49);
            this.lblA.Name = "lblA";
            this.lblA.Size = new System.Drawing.Size(16, 13);
            this.lblA.TabIndex = 1;
            this.lblA.Text = "a:";
            // 
            // lblB
            // 
            this.lblB.AutoSize = true;
            this.lblB.Location = new System.Drawing.Point(12, 85);
            this.lblB.Name = "lblB";
            this.lblB.Size = new System.Drawing.Size(16, 13);
            this.lblB.TabIndex = 2;
            this.lblB.Text = "b:";
            // 
            // lblC
            // 
            this.lblC.AutoSize = true;
            this.lblC.Location = new System.Drawing.Point(12, 122);
            this.lblC.Name = "lblC";
            this.lblC.Size = new System.Drawing.Size(16, 13);
            this.lblC.TabIndex = 3;
            this.lblC.Text = "c:";
            // 
            // txtA
            // 
            this.txtA.Location = new System.Drawing.Point(34, 46);
            this.txtA.Name = "txtA";
            this.txtA.Size = new System.Drawing.Size(360, 20);
            this.txtA.TabIndex = 4;
            // 
            // txtB
            // 
            this.txtB.Location = new System.Drawing.Point(34, 82);
            this.txtB.Name = "txtB";
            this.txtB.Size = new System.Drawing.Size(360, 20);
            this.txtB.TabIndex = 5;
            // 
            // txtC
            // 
            this.txtC.Location = new System.Drawing.Point(34, 122);
            this.txtC.Name = "txtC";
            this.txtC.Size = new System.Drawing.Size(360, 20);
            this.txtC.TabIndex = 6;
            // 
            // btnCalculate
            // 
            this.btnCalculate.Location = new System.Drawing.Point(175, 154);
            this.btnCalculate.Name = "btnCalculate";
            this.btnCalculate.Size = new System.Drawing.Size(75, 23);
            this.btnCalculate.TabIndex = 7;
            this.btnCalculate.Text = "Calculate!";
            this.btnCalculate.UseVisualStyleBackColor = true;
            this.btnCalculate.Click += new System.EventHandler(this.btnCalculate_Click);
            // 
            // lblSolutions
            // 
            this.lblSolutions.AutoSize = true;
            this.lblSolutions.Location = new System.Drawing.Point(31, 226);
            this.lblSolutions.Name = "lblSolutions";
            this.lblSolutions.Size = new System.Drawing.Size(53, 13);
            this.lblSolutions.TabIndex = 8;
            this.lblSolutions.Text = "Solutions:";
            // 
            // txtSolution1
            // 
            this.txtSolution1.Location = new System.Drawing.Point(34, 242);
            this.txtSolution1.Name = "txtSolution1";
            this.txtSolution1.ReadOnly = true;
            this.txtSolution1.Size = new System.Drawing.Size(165, 20);
            this.txtSolution1.TabIndex = 9;
            // 
            // txtSolution2
            // 
            this.txtSolution2.Location = new System.Drawing.Point(222, 242);
            this.txtSolution2.Name = "txtSolution2";
            this.txtSolution2.ReadOnly = true;
            this.txtSolution2.Size = new System.Drawing.Size(172, 20);
            this.txtSolution2.TabIndex = 10;
            // 
            // chkImaginary
            // 
            this.chkImaginary.AutoSize = true;
            this.chkImaginary.Location = new System.Drawing.Point(33, 189);
            this.chkImaginary.Name = "chkImaginary";
            this.chkImaginary.Size = new System.Drawing.Size(71, 17);
            this.chkImaginary.TabIndex = 11;
            this.chkImaginary.Text = "Imaginary";
            this.chkImaginary.UseVisualStyleBackColor = true;
            // 
            // QuadraticSolver
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(406, 285);
            this.Controls.Add(this.chkImaginary);
            this.Controls.Add(this.txtSolution2);
            this.Controls.Add(this.txtSolution1);
            this.Controls.Add(this.lblSolutions);
            this.Controls.Add(this.btnCalculate);
            this.Controls.Add(this.txtC);
            this.Controls.Add(this.txtB);
            this.Controls.Add(this.txtA);
            this.Controls.Add(this.lblC);
            this.Controls.Add(this.lblB);
            this.Controls.Add(this.lblA);
            this.Controls.Add(this.lblPrompt);
            this.Name = "QuadraticSolver";
            this.Text = "Quadratic Solver";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label lblPrompt;
        private System.Windows.Forms.Label lblA;
        private System.Windows.Forms.Label lblB;
        private System.Windows.Forms.Label lblC;
        private System.Windows.Forms.TextBox txtA;
        private System.Windows.Forms.TextBox txtB;
        private System.Windows.Forms.TextBox txtC;
        private System.Windows.Forms.Button btnCalculate;
        private System.Windows.Forms.Label lblSolutions;
        private System.Windows.Forms.TextBox txtSolution1;
        private System.Windows.Forms.TextBox txtSolution2;
        private System.Windows.Forms.CheckBox chkImaginary;
    }
}

Вот код моей программы, который выполняет фактическую обработку данных:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

        private void btnCalculate_Click(object sender, EventArgs e)
        {
            if (txtA.Text == "" || txtB.Text == "" || txtC.Text == "")
            {
                string stringSol = "Please enter some values!";
                txtSolution1.Text = stringSol;
                txtSolution2.Text = stringSol;
            }
            double aValue = double.Parse(txtA.Text);
            double bValue = double.Parse(txtB.Text);
            double cValue = double.Parse(txtC.Text);

            double solution1Double, solution2Double;

            //Quadratic Formula: x = (-b +- sqrt(b^2 - 4ac)) / 2a

            //Calculate discriminant
            double insideSquareRoot = (bValue * bValue) - 4 * aValue * cValue;

            if (insideSquareRoot < 0)
            {
                //No real solution
                solution1Double = Double.NaN;
                solution2Double = Double.NaN;

                txtSolution1.Text = solution1Double.ToString();
                txtSolution2.Text = solution2Double.ToString();
            }
            else if (insideSquareRoot == 0)
            {
                //One real solution
                double sqrtOneSolution = Math.Sqrt(insideSquareRoot);
                solution1Double = (-bValue + sqrtOneSolution) / (2 * aValue);
                solution2Double = double.NaN;

                txtSolution1.Text = solution1Double.ToString();
                txtSolution2.Text = solution2Double.ToString();
            }
            else if (insideSquareRoot > 0)
            {
                //Two real solutions
                double sqrtTwoSolutions = Math.Sqrt(insideSquareRoot);
                solution1Double = (-bValue + sqrtTwoSolutions) / (2 * aValue);
                solution2Double = (-bValue - sqrtTwoSolutions) / (2 * aValue);

                txtSolution1.Text = solution1Double.ToString();
                txtSolution2.Text = solution2Double.ToString();
            }
        }
    }
}

Ответы [ 4 ]

3 голосов
/ 08 ноября 2010

Вы можете использовать метод double.TryParse.

Это лучше, чем проверка на == "", так как он скажет вам, что вы не можете анализировать "Hello" как двойное тоже.

Вам также необходимо вернуться из обработчика событий, если один из TryParse возвращает false.

2 голосов
/ 08 ноября 2010

Вместо этого вы можете использовать NumericUpDown .Вам гарантировано, что вход от этого элемента управления будет числовым.Тогда весь код, который требуется:

double userNumber = myNumUpDown.Value;

Можно даже ограничить ввод числа, чтобы убедиться, что он попадает в заданный вами диапазон

myNumUpDown.Minimum = 300;
myNumUpDown.Maximum = 500;

Наряду со многими другими вещами.Наконец, он даже поставляется с элементами управления GUI вверх / вниз, так что ваши пользователи могут быть очень ленивыми и вводить число с помощью мыши!

alt text

1 голос
/ 21 марта 2012

Вы можете попробовать этот формат, замените textbox1 на имя вашего текстового поля.

int a = textbox1.Text != "" ? Convert.ToInt32(textbox1.Text) : 0;
int b = textbox2.Text != "" ? Convert.ToInt32(textbox2.Text) : 0;
int total = a + b;

Вы можете переназначить результат следующим образом:

textbox3 = total.toString();
0 голосов
/ 08 ноября 2010

if (txtA.Text == "" || txtB.Text == "" || txtC.Text == "")
            {
                string stringSol = "Please enter some values!";
                txtSolution1.Text = stringSol;
                txtSolution2.Text = stringSol;
                return;
            }

...