首页 > 解决方案 > 我正在尝试在上传到数据库之前验证用户输入。我已链接我的验证和主代码,但我一直收到错误

问题描述

错误:

System.FormatException: '输入字符串的格式不正确。'

我让用户输入表单,但在接受之前必须对其进行验证(以 开头IsFilledIn())。我已将表单中文本框中的字符串解析为 int,以便它可以进入数据库。当我点击提交时,它似乎完全跳过了验证,但已经包含了所有需要的内容(我认为)。

当前代码:

表格1:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Lab5_validation;
using System.Data.SqlClient;

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

        private void btnsubmit_Click(object sender, EventArgs e)
        {
            Character temp = new Character();

            //Sets temporary Variables
            temp.CharName = txtCharName.Text;
            temp.Health = Int32.Parse(txtHealth.Text);
            temp.Lvl = Int32.Parse(txtLvl.Text);
            temp.Agility = Int32.Parse(txtAgility.Text);
            temp.Strength = Int32.Parse(txtStrength.Text);
            temp.Stamina = Int32.Parse(txtStamina.Text);
            temp.Armor = Int32.Parse(txtArmor.Text);
            temp.HoursPlayed = Double.Parse(txtHoursPlayed.Text);
            temp.PlayedSince = DateTime.Parse(txtPlayedSince.Text);
            temp.Cass = txtClass.Text;

            if (!temp.Feedback.Contains("ERROR:"))
            {
                Feedback.Text = temp.AddARecord();
            }
            else
            {
                Feedback.Text = temp.Feedback;
            }
        }
    }
}

字符.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using Lab5_validation;

namespace FinalAJG
{
    class Character
    {
        //Define PRIVATE variables.
        bool blnResult;
        private string charname;
        private string cass;
        private int health;
        private int lvl;
        private int agility;
        private int strength;
        private int stamina;
        private int armor;
        private double hoursplayed;
        private DateTime playedsince;
        private float AvgPlayTime=777;
        private int TotalPoints=444;
        public string feedback = "";

        // Creates Public variables the users can input to, then stores them to private variable if validated correctly.
        public string CharName
        {
            get
            {
                //Returns private variable to class.
                return charname;
            }
            set
            {
                //IF-ELSE statement to validate user input.
                if (ValidationLibrary.IsItFilledIn(value))
                {
                    // Sets private variable 'fName' to equal user input on public variable.
                    charname = value;
                }
                else
                {
                    //If they enter invalid input, the feed back will be set to an error message, and the private variable will not be set.
                    feedback += "\n\nERROR: Enter your charcters name!!!";
                }
            }
        }

        //Public variable to receive user input securly.
        public string Cass
        {
            get
            {
                //Returns Private variable
                return cass;
            }
            set
            {   //IF-ELSE statement to validate user input.
                if (ValidationLibrary.IsItFilledIn(value))
                {
                    cass = value; // Sets Private Variable

                }
                else
                {//Feedback gives error IF validation
                    feedback += "\n\nERROR: Enter your Class!(ONLY OPTIONS ARE, Mage, Assassin, Warrior, Archer, Druid, and Warlock!!";

                }
            }
        }

        //Same as previous Public Variables
        public int Health
        {
            get
            {
                return health;
            }
            set
            {   //Checks for user input, if not true give error feedback.
                if (ValidationLibrary.IsItFilledIn(value.ToString()))
                {
                    health = value;

                }
                else
                {
                    feedback += "\n\nERROR: Enter Characters Health (25-100)!!   ";
                }
            }

        }

        //Same as previous Public Variables
        public int Lvl
        {
            get
            {
                return lvl;
            }
            set
            {
                if (ValidationLibrary.IsItFilledIn(value.ToString()))
                {
                    lvl = value;
                }
                else
                {
                    feedback += "\n\nERROR:Enter your Characters level! (1-80)\n  ";
                }
            }
        }

        //Same as previous Public Variables, except it will not be required to fill it in.
        public int Agility
        {
            get
            {
                return agility;
            }
            set
            {
                if (ValidationLibrary.IsItFilledIn(value.ToString()))
                {
                    agility = value;
                }
                else
                {
                    feedback += "\n\nERROR:Enter valid Date!! (02-20-2020, 11/11/2011, 06/24/2019)";
                }
            }
        }

        //Same as previous Public Variables
        public int Strength
        {
            get
            {
                return strength;
            }
            set
            {
                //Validates to ensure the required length of zipcode is entered
                if (ValidationLibrary.IsItFilledIn(value.ToString()))
                {
                    do
                    {
                        strength = value;
                    } while (blnResult == true);
                }
                else
                {
                    feedback += "\n\nERROR:Enter Characters strength!! (1-25)  ";
                }
            }
        }

        //Same as previous Public Variables
        public int Stamina
        {
            get
            {
                return stamina;
            }
            set
            {
                if (ValidationLibrary.IsItFilledIn(value.ToString()))
                {
                    stamina = value;
                }
            }
        }

        //Same as previous Public Variables except the validation checks for valid characters and the correct length
        public int Armor
        {
            get
            {
                return armor;
            }
            set
            {
                if (ValidationLibrary.IsItFilledIn(value.ToString()))
                {
                    armor = value;
                }
                else
                {
                    feedback += "\n\nERROR:Enter Valid armor rating!! (10-50) ";
                }

            }
        }

        //Same as previous Public Variables
        public double HoursPlayed
        {
            get
            {
                return hoursplayed;
            }
            set
            {
                if (ValidationLibrary.IsItFilledIn(value.ToString()))
                {
                        hoursplayed = value;
                }
                else
                {
                    feedback += "\n\nERROR:Enter Valid Number!!(.5, 2.3, 6.4, 92)";
                }
            }
        }

        //Same as previous Public Variables except checks for required characters for a valid Email.
        public DateTime PlayedSince
        {
            get
            {
                return playedsince;
            }
            set
            {
                if (ValidationLibrary.IsItFilledIn(value.ToString()))
                {
                    playedsince = value;
                }
                else
                {
                    feedback += "\n\nERROR:Enter valid Date!! (02-20-2020, 11/11/2011, 06/24/2019)";
                }
            }
        }

        // Feedback variable to display results or error message.
        public string Feedback
        {
            get
            {
                return feedback;
            }
            set
            {   // IF feedback contains 'ERROR' then leave it blank and display which input was incorrect
                if (feedback.Contains("ERROR:"))
                {
                    feedback += "";
                }
                //ELSE, store and display the results.
                else
                {
                    feedback = value;
                }
            }
        }

        public string AddARecord()
        {
            //Init string var
            string strResult = "";

            //Make a connection object
            SqlConnection Conn = new SqlConnection();

            //Initialize it's properties
            Conn.ConnectionString = ********************";//Set the Who/What/Where of DB

            //Sends command to SQL Server
            string strSQL = "INSERT INTO Chars (CharName, Class, Health, Lvl, Agility, Strength, Stamina, Armor, HoursPlayed, PlayedSince, AvgPlayTime, TotalPoints) VALUES (@CharName, @Class, @Health, @Level, @Agility, @Strength, @Stamina, @Armor, @HoursPlayed, @PlayedSince, @AvgPlayTime, @TotalPoints)";

            // Sends out Command
            SqlCommand comm = new SqlCommand();
            comm.CommandText = strSQL;  //Commander knows what to say
            comm.Connection = Conn;     //Where's the phone?  Here it is

            // Adds all parameters.
            comm.Parameters.AddWithValue("@CharName", CharName);
            comm.Parameters.AddWithValue("@Class", Cass);
            comm.Parameters.AddWithValue("@Health", Health);
            comm.Parameters.AddWithValue("@Level", Lvl);
            comm.Parameters.AddWithValue("@Agility", Agility);
            comm.Parameters.AddWithValue("@Strength", Strength);
            comm.Parameters.AddWithValue("@Stamina", Stamina);
            comm.Parameters.AddWithValue("@Armor", Armor);
            comm.Parameters.AddWithValue("@HoursPlayed", HoursPlayed);
            comm.Parameters.AddWithValue("@PlayedSince", PlayedSince);
            comm.Parameters.AddWithValue("@AvgPlayTime", AvgPlayTime);
            comm.Parameters.AddWithValue("@TotalPoints", TotalPoints);

            //Attempts to connect to the Database server
            try
            {
                //Calls to the database server, like dialing a phone.
                Conn.Open();
                int intRecs = comm.ExecuteNonQuery();
                //Output to rhe user the success of inserting records
                strResult = $"SUCCESS: Inserted {intRecs} records.";
                //Close the Connection to Database Server
                Conn.Close();
            }
            //This will catch any errors if we run into issues connecting.
            catch (Exception err)
            {
                //Displays The Error.
                strResult = "ERROR: " + err.Message;
            }
            finally
            {
            }
            return strResult;
        }

        public DataSet SearchPerson(String strCharName, String strCharID)
        {
            //Create a dataset to return filled
            DataSet ds = new DataSet();

            //Create a command for our SQL statement
            SqlCommand comm = new SqlCommand();

            //Write a Select Statement to perform Search
            String strSQL = "SELECT CharID, CharName, Class, Health, Level, Agility, Strength, Armor, HoursPlayed, PlayedSince, AvgPlayTime, TotalPoints FROM Chars WHERE 0=0";

            //If the First/Last Name is filled in include it as search criteria
            if (strCharName.Length > 0)
            {
                strSQL += " AND CharName LIKE @CharName";
                comm.Parameters.AddWithValue("@CharName", "%" + strCharName + "%");
            }
            if (strCharID.Length > 0)
            {
                strSQL += " AND CharID LIKE @CharID";
                comm.Parameters.AddWithValue("@CharID", "%" + strCharID + "%");
            }
            //Create DB tools and Configure
            //*********************************************************************************************
            SqlConnection conn = new SqlConnection();
            //Create the who, what where of the DB
            string strConn = @GetConnected();
            conn.ConnectionString = strConn;

            //Fill in basic info to command object
            comm.Connection = conn;     //tell the commander what connection to use
            comm.CommandText = strSQL;  //tell the command what to say

            //Create Data Adapter
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = comm;    //commander needs a translator(dataAdapter) to speak with datasets

            //*********************************************************************************************

            //Get Data
            conn.Open();                //Open the connection (pick up the phone)
            da.Fill(ds, "Chars_Temp");     //Fill the dataset with results from database and call it "EBooks_Temp"
            conn.Close();               //Close the connection (hangs up phone)

            //Return the data
            return ds;
        }

        private string GetConnected()
        {
            return ************************
        }

        // Initialize Public Class from person().
        public Character()
        {
            charname = "";
            cass = "";
            health = 25;
            lvl = 1;
            agility = 1;
            strength = 1;
            stamina = 1;
            armor = 10;
            hoursplayed = 0;
            playedsince = DateTime.Now;
            feedback = "";
        }
    }
}

验证:

//Allen J. Gawlowicz
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace Lab5_validation
{
    public class ValidationLibrary
    {
        bool result = false;
        string temp;

        //Validates for alphabetical input only.
        public static bool Goodchar(string temp) 
        {
            bool result = false;
            string strGoodChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            // FOR EACH charcacter in Variable, check to make sure it is Alphabetical
            foreach (char ch in strGoodChars.ToUpper())
            {//If the variable contains only alphabetical, result= true.
                if (temp.Contains(ch))
                {
                    result = true;
                }
                
            }
            return result;
        }
       
        //Checks to see if user inputs a bad word.
        public static bool GotBadWords(string temp)
        {
            bool result = false;
            //Array which holds all bad words to ever exist!!
            string[] strBadwords = { "POOP", "HOMEWORK", "CACA" };
                // FOR EACH word in the array it checks to see if input value  matches.
                foreach (string strBW in strBadwords)
                {
                    if (temp.Contains(strBW))
                    {
                        result = true;
                    }
                }
            return result;
        }

        //Function which checks if user inputs.
        public static bool IsItFilledIn(string temp)
        {
            bool result = false;
            //If the number of characters entered is greater than 0 (then obviously), it is filled in (true).
            if (temp.Length > 0)
            {
                result = true;
            }
            return result;
        }

        //Function which checks if user input is a future date.
        public static bool IsAFutureDate(DateTime temp)
        {
            bool blnResult;
            //IF usrr input is today or before, then blnRes = false.
            if (temp <= DateTime.Now)
            {
                blnResult = false;
            }
            else
            {
                blnResult = true;
            }

            return blnResult;
        }

        //Function which checks user email input for '@' and '.'.
        public static bool IsValidEmail(string temp)
        {
            bool blnResult = true;

            int atLocation = temp.IndexOf("@");
            int NexttatLocation = temp.IndexOf("@", atLocation + 1);

            int periodLocation = temp.LastIndexOf(".");

            if (temp.Length < 8)
            {
                blnResult = false;
            }
            else if (atLocation < 2)
            {
            }
            else if (periodLocation + 2 > (temp.Length))
            {
                blnResult = false;
            }

            return blnResult;
        }

        //Function which checks for '.' in the input URL.
        public static bool IsValidUrl(string temp)
        {
            bool blnResult = true;
            int NexttatLocation = temp.IndexOf(".");
            int periodLocation = temp.LastIndexOf(".");

            if (temp.Length < 10)
            {
                blnResult = false;
            }
            else if (periodLocation + 2 > (temp.Length))
            {
                blnResult = false;
            }

            return blnResult;
        }

        //Function which checks user input for a specific length. ('min' will changed depending on variable in main program).
        public static bool IsMinimumAmount(string temp, int min)
        {
            bool blnResult;

            if (temp.Length >= min)
            {
                blnResult = true;
            }
            else
            {
                blnResult = false;
            }

            return blnResult;
        }

        public static bool IsMinimumAmount(double temp, double min)
        {
            bool blnResult;

            if (temp >= min)
            {
                blnResult = true;
            }
            else
            {
                blnResult = false;
            }

            return blnResult;
        }
    }
}

程序.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Lab5_validation;

namespace FinalAJG
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

标签: c#sql-server

解决方案


您的Parse方法不能接受空字符串。相反,我建议TryParse,它将尝试解析字符串,如果失败,那么您将获得分配目标的默认值。所以如果你这样做:

int.TryParse(txtHealth.Text, out temp.Health);

的值temp.Health将是字符串的解析值,或者它将是默认值(即0for int)。

double和可以使用相同的方法DateTime,因此:

double.TryParse(txtHoursPlayed.Text, out temp.HoursPlayed);

DateTime.TryParse(txtPlayedSince.Text, out temp.PlayedSince);

或者,您可以检查输入字符串IsNullOrWhiteSpace是否为true

temp.Health = string.IsNullOrWhiteSpace(txtHealth.Text) ? 0 : int.Parse(txtHealth.Text);

但当然,这些TryParse方法通常更清洁。


推荐阅读