Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我试图在上传到数据库之前验证用户输入。我已经链接了验证和主代码,但我一直收到一个错误_C#_Sql - Fatal编程技术网

C# 我试图在上传到数据库之前验证用户输入。我已经链接了验证和主代码,但我一直收到一个错误

C# 我试图在上传到数据库之前验证用户输入。我已经链接了验证和主代码,但我一直收到一个错误,c#,sql,C#,Sql,错误:System.FormatException:“输入字符串的格式不正确。” 我正在将用户输入表单中,但在接受之前必须对其进行验证(从IsFilledIn()开始)。我已经将表单中文本框中的字符串解析为int,这样它就可以进入数据库。当我点击提交时,它似乎完全跳过了验证,但已经包含了所有需要的内容(我认为) 当前代码: 表格1: 使用制度; 使用System.Collections.Generic; 使用系统组件模型; 使用系统数据; 使用系统图; 使用System.Linq; 使用系统文本

错误:System.FormatException:“输入字符串的格式不正确。” 我正在将用户输入表单中,但在接受之前必须对其进行验证(从IsFilledIn()开始)。我已经将表单中文本框中的字符串解析为int,这样它就可以进入数据库。当我点击提交时,它似乎完全跳过了验证,但已经包含了所有需要的内容(我认为)

当前代码:
表格1:
使用制度;
使用System.Collections.Generic;
使用系统组件模型;
使用系统数据;
使用系统图;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows.Forms;
使用Lab5_验证;
使用System.Data.SqlClient;
名称空间FinalAJG
{
公共部分类Form1:Form
{
公共表格1()
{
初始化组件();
}
私有void Form1\u加载(对象发送方、事件参数e)
{
}
私有void btnsubmit\u单击(对象发送者,事件参数e)
{
字符临时=新字符();
//设置临时变量
temp.CharName=txtCharName.Text;
temp.Health=Int32.Parse(txthhealth.Text);
temp.Lvl=Int32.Parse(txtLvl.Text);
temp.Agility=Int32.Parse(txtAgility.Text);
temp.Strength=Int32.Parse(txtStrength.Text);
temp.Stamina=Int32.Parse(txtdatamina.Text);
temp.Armor=Int32.Parse(txtArmor.Text);
temp.HoursPlayed=Double.Parse(txtHoursPlayed.Text);
temp.PlayedSince=DateTime.Parse(txtPlayedSince.Text);
temp.Cass=txtClass.Text;
如果(!temp.Feedback.Contains)(“错误:”)
{
Feedback.Text=temp.AddARecord();
}
其他的
{
反馈文本=临时反馈;
}
}
}
}
Character.cs:
使用制度;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用系统数据;
使用System.Data.SqlClient;
使用Lab5_验证;
名称空间FinalAJG
{
类字符
{
//定义私有变量。
布尔·布尔诺;
私有字符串字符名;
私有字符串cass;
私人卫生;
私人国际级;
私密性和灵活性;
私人综合实力;
个人耐力;
私人装甲;
私人双人小时;
私人日期时间播放自;
私人浮动AvgPlayTime=777;
私人积分总数=444;
公共字符串反馈=”;
//创建用户可以输入的公共变量,如果验证正确,则将其存储到私有变量。
公共字符串字符名
{
得到
{
//将私有变量返回给类。
返回charname;
}
设置
{
//用于验证用户输入的IF-ELSE语句。
if(ValidationLibrary.IsItFilledIn(值))
{
//将私有变量“fName”设置为等于用户对公共变量的输入。
charname=值;
}
其他的
{
//如果输入无效输入,反馈将设置为错误消息,并且不会设置私有变量。
反馈+=“\n\n错误:输入您的角色名称!!!”;
}
}
}
//用于安全接收用户输入的公共变量。
公共字符串Cass
{
得到
{
//返回私有变量
返回cass;
}
设置
{//IF-ELSE语句来验证用户输入。
if(ValidationLibrary.IsItFilledIn(值))
{
cass=value;//设置私有变量
}
其他的
{//如果验证失败,反馈将出错
反馈+=“\n\n错误:进入你的职业!(只有法师、刺客、战士、弓箭手、德鲁伊和术士!!”;
}
}
}
//与前面的公共变量相同
公共卫生
{
得到
{
恢复健康;
}
设置
{//检查用户输入,如果不正确,则给出错误反馈。
if(ValidationLibrary.IsItFilledIn(value.ToString()))
{
健康=价值;
}
其他的
{
反馈+=“\n\n错误:输入字符健康(25-100)!!”;
}
}
}
//与前面的公共变量相同
公共国际级
{
得到
{
返回lvl;
}
设置
{
if(ValidationLibrary.IsItFilledIn(value.ToString()))
{
lvl=数值;
}
其他的
{
反馈+=“\n\n错误:输入您的字符级别!(1-80)\n”;
}
}
}
//与前面的公共变量相同,只是不需要填写它。
公共智能
{
得到
{
返回敏捷性;
}
设置
{
if(ValidationLibrary.IsItFilledIn(value.ToString()))
{
敏捷=价值;
}
其他的
{
反馈+=“\n\n错误:输入有效日期!!(2020年2月20日,2011年11月11日,2019年6月24日)”;
}
}
}
//与前面的公共变量相同
公共int Str
Current Code:
Form1:
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 Form1_Load(object sender, EventArgs e)
        {

        }

        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;
            }
        }
    }
}

Character.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 charecters 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 = "";

        }


    }
}
Validation:
//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 Alphebtical 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 ammount of charcters entered is greater than 0 (then obvously), 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;
        }
    }
}

Program.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());
        }
    }
}