mscorlib.dll中出现未处理的“System.FormatException”类型异常附加信息:输入字符串的格式不正确

时间:2017-03-31 14:48:41

标签: c# sql-server sql-server-2008

我正在尝试将表单数据插入到数据库中,但是代码存在一些问题,我无法识别它。错误是:

  

mscorlib.dll中发生了未处理的“System.FormatException”类型异常   附加信息:输入字符串的格式不正确。

Winform代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MobShopManagSys
{
    public partial class Product_AddForm : Form
    {
        ProductsDB db = new ProductsDB();
        public Product_AddForm()
        {
            InitializeComponent();
        }
        private void SaveButton_Click(object sender, EventArgs e)
        {
            if (IsValidated()) //Proceed if required data is entered
            {
                db.InsertProductInDB(NameTextBox.Text, Convert.ToInt32(CategoryComboBox.SelectedValue), ModelTextBox.Text, SeriesComboBox.Text, Convert.ToInt32(SIMSlotsComboBox.Text), CarrierTypeComboBox.Text, GetReleaseDate(), Convert.ToInt32(RAMTextBox.Text), RAMMemUnitComboBox.Text, Convert.ToInt32(SecondryMemTextBox.Text), SecondMemUnitComboBox.Text, Convert.ToInt32(ExpandableTextBox.Text), ExpandableMemUnitComboBox.Text, OSVersionComboBox.Text, ProcessorComboBox.Text, ScreenSizeTextBox.Text, ScreenSizeTypeComboBox.Text, Convert.ToInt32(BatteryTextBox.Text), BatteryTypeComboBox.Text, CommentsTextBox.Text, Convert.ToInt32(SupplierComboBox.SelectedValue), float.Parse(PriceTextBox.Text), PriceUnitComboBox.Text, Convert.ToInt32(QuantityTextBox.Text), SaveProductPhoto());
                MessageBox.Show("New Record is added successfully!", "Record Added", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void CloseButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void AddSupplierButton_Click(object sender, EventArgs e)
        {
            Suppliers_AddForm AddNewSupplierFrm = new Suppliers_AddForm();
            AddNewSupplierFrm.ShowDialog();
            //Reload Data into control
            LoadFormControlsData();

        }
        private void ResetButton_Click(object sender, EventArgs e)
        {
            NameTextBox.Clear();
            CategoryComboBox.Text = " ";
            ModelTextBox.Clear();
            SeriesComboBox.Text = null;
            CarrierTypeComboBox.Text = null;
            SIMSlotsComboBox.Text = null;
            ReleaseDateTimePicker.CustomFormat = " ";

            RAMTextBox.Clear();
            RAMMemUnitComboBox.Text = null;
            SecondryMemTextBox.Clear();
            SecondMemUnitComboBox.Text = null;
            ExpandableTextBox.Clear();
            ExpandableMemUnitComboBox.Text = null;

            OSVersionComboBox.Text = null;
            ProcessorComboBox.Text = null;
            ScreenSizeTextBox.Clear();
            ScreenSizeTypeComboBox.Text = null;
            BatteryTextBox.Clear();
            BatteryTypeComboBox.Text = null;

            CommentsTextBox.Clear();

            SupplierComboBox.Text = null;
            PriceTextBox.Clear();
            PriceUnitComboBox.Text = null;
            QuantityTextBox.Clear();

            SystemSounds.Beep.Play();
            NameTextBox.Focus();
        }
        private void Product_AddForm_Load(object sender, EventArgs e)
        {
            LoadFormControlsData();
        }

        private void LoadFormControlsData()
        {
            CategoryComboBox.DataSource = db.LoadCategoryComboBox();
            CategoryComboBox.DisplayMember = "CategoryName";
            CategoryComboBox.ValueMember = "CategoryID";
            CategoryComboBox.SelectedIndex = -1;


            SeriesComboBox.DataSource = db.LoadSeriesComboBox();
            SeriesComboBox.DisplayMember = "Series";

            SupplierComboBox.DataSource = db.LoadSupplierComboBox();
            SupplierComboBox.DisplayMember = "Name";
            SupplierComboBox.ValueMember = "SupplierID";
            SupplierComboBox.SelectedIndex = -1;
        }
        private void AddNewCategoryButton_Click(object sender, EventArgs e)
        {
            Categories_AddForm AddCategoryFrm = new Categories_AddForm();
            AddCategoryFrm.ShowDialog();

            LoadFormControlsData();
        }
        private void ProductImagePictureBox_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "Select the Image";
            ofd.Filter = "Image File (*.png;*.jpg;*.bmp;*.gif)|*.png;*.jpg;*.bmp;*.gif";

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                ProductImagePictureBox.Image = new Bitmap(ofd.FileName);
            }
        }
        private byte[] SaveProductPhoto()
        {
            MemoryStream ms = new MemoryStream();
            ProductImagePictureBox.Image.Save(ms, ProductImagePictureBox.Image.RawFormat);
            return ms.GetBuffer();
        }
    private bool IsValidated()  //Validation Method Defination
        {
            if (NameTextBox.Text.Trim() == "")
            {
                ValidationMessage(NameTextBox, "Name is required!");
                return false;
            }
            if (CategoryComboBox.Text.Trim() == "")
            {
                ValidationMessage(CategoryComboBox, "Please select the Category/Brand!");
                return false;
            }
            if (ModelTextBox.Text.Trim() == "")
            {
                ValidationMessage(ModelTextBox, "Model is required!");
                return false;
            }
            if (RAMTextBox.Text.Trim() == "")
            {
                ValidationMessage(RAMTextBox, "RAM memory required!");
                return false;
            }
            else
            {
                float outRAM;
                if(!float.TryParse(RAMTextBox.Text, out outRAM))
                {
                    ValidationMessage(RAMTextBox, "RAM field only contain numbers!");
                    return false;
                }
            }
            if (RAMMemUnitComboBox.Text.Trim() == "")
            {
                ValidationMessage(RAMMemUnitComboBox, "Please select a Memory Unit!");
                return false;
            }

            if (SecondryMemTextBox.Text.Trim() == "")
            {
                ValidationMessage(SecondryMemTextBox, "Secondry memory field is required!");
                return false;
            }
            else
            {
                float outSecMem;
                if (!float.TryParse(RAMTextBox.Text, out outSecMem))
                {
                    ValidationMessage(RAMTextBox, "Secondry memory field only contain numbers!");
                    return false;
                }
            }
            if (SecondMemUnitComboBox.Text.Trim() == "")
            {
                ValidationMessage(SecondMemUnitComboBox, "Please select a Memory Unit!");
                return false;
            }
            if (ExpandableTextBox.Text != "")
            {
                int outexpmem;
                if (!int.TryParse(ExpandableTextBox.Text, out outexpmem))
                {
                    ValidationMessage(ExpandableTextBox, "Expandable memory can only numbers!");
                    return false;
                }
              if (ExpandableMemUnitComboBox.Text.Trim() == "")
                {
                    ValidationMessage(ExpandableMemUnitComboBox, "Please select a Memory Unit!");
                    return false;
                }
            }
            if (OSVersionComboBox.Text.Trim() == "")
            {
                ValidationMessage(OSVersionComboBox, "OS Version selection is required!");
                return false;
            }
            if (BatteryTextBox.Text.Trim() == "")
            {
                ValidationMessage(BatteryTextBox, "Battery Capacity required!");
                return false;
            }
            if (BatteryTypeComboBox.Text.Trim() == "")
            {
                ValidationMessage(BatteryTypeComboBox, "Please select a Battery Capacity Unit!");
                return false;
            }
            if(PriceTextBox.Text != "" )
            {
                float outexpmem;
                if (!float.TryParse(PriceTextBox.Text, out outexpmem))
                {
                    ValidationMessage(PriceTextBox, "Purchase Price only numbers!");
                    return false;
                }
              if (PriceUnitComboBox.Text.Trim() == "")
                {
                    ValidationMessage(PriceUnitComboBox, "Please select Currency Unit!");
                    return false;
                }
            }

            if (QuantityTextBox.Text.Trim() == "")
            {
                ValidationMessage(QuantityTextBox, "Quantity of Product is required!");
                return false;
            }
            else
            {
                int outQuantity;
                if (!int.TryParse(QuantityTextBox.Text, out outQuantity))
                {
                    ValidationMessage(QuantityTextBox, "Quantity can only in numbers!");
                    return false;
                }
             }
            return true;
            }

        private void ValidationMessage(Control ctrl, string ValidationMsg) //Validation Message Def.
        {
            ctrl.BackColor = Color.LightPink;
            MessageBox.Show(ValidationMsg, "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            ctrl.Focus();
        }

        private void ctrl_TextChanged(object sender, EventArgs e) //Back change color to white
        {
            Control ctrl = (Control)sender;
            ctrl.BackColor = Color.White;
        }
        private void ClearCommentsButton_Click(object sender, EventArgs e)
        {
            CommentsTextBox.Clear();
            CommentsTextBox.Focus();
        }
        //Date Time Picker   <Start>
        private void ReleaseDateTimePicker_ValueChanged(object sender, EventArgs e)
        {
            ReleaseDateTimePicker.CustomFormat = "dd/MM/yyyy";
        }

        private void ReleaseDateTimePicker_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode==Keys.Back || e.KeyCode == Keys.Delete)
            {
                ReleaseDateTimePicker.CustomFormat = " ";
            }
        }
        private DateTime? GetReleaseDate()
        {
            if (ReleaseDateTimePicker.Text.Trim() == string.Empty)
            {
                return (DateTime?)null;
            }
            else
                return ReleaseDateTimePicker.Value.Date;
        }


    }  //Date Time Picker   <End>

}

这行代码出错:

db.InsertProductInDB(NameTextBox.Text, Convert.ToInt32(CategoryComboBox.SelectedValue), ModelTextBox.Text, SeriesComboBox.Text, Convert.ToInt32(SIMSlotsComboBox.Text), CarrierTypeComboBox.Text, GetReleaseDate(), Convert.ToInt32(RAMTextBox.Text), RAMMemUnitComboBox.Text, Convert.ToInt32(SecondryMemTextBox.Text), SecondMemUnitComboBox.Text, Convert.ToInt32(ExpandableTextBox.Text), ExpandableMemUnitComboBox.Text, OSVersionComboBox.Text, ProcessorComboBox.Text, ScreenSizeTextBox.Text, ScreenSizeTypeComboBox.Text, Convert.ToInt32(BatteryTextBox.Text), BatteryTypeComboBox.Text, CommentsTextBox.Text, Convert.ToInt32(SupplierComboBox.SelectedValue), float.Parse(PriceTextBox.Text), PriceUnitComboBox.Text, Convert.ToInt32(QuantityTextBox.Text), SaveProductPhoto());

数据库类代码

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

namespace MobShopManagSys
{
    class ProductsDB
    {
        string connString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

        //Add Product Form
        public void InsertProductInDB(string Name, int CategoryID, string Model, string Series, int SIMSlots, string CarrierType, DateTime? ReleaseDate, int RAM, string RAMMemUnit, int SecondryMem, string SecondMemUnit, int Expandable, string ExpandableMemUnit, string OSVersion, string Processor, string ScreenSize, string ScreenSizeType, int Battery, string BatteryType, string Comments, int SupplierID, float Price, string PriceUnit, int UnitsInStock, byte[] SaveProductPhoto)
        {
            using (SqlConnection conn = new SqlConnection(connString))
            {
                using (SqlCommand cmd = new SqlCommand("spProducts_InsertProduct", conn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    //Parameters
                    cmd.Parameters.AddWithValue("@Name", Name);
                    cmd.Parameters.AddWithValue("@CategoryID", CategoryID);
                    cmd.Parameters.AddWithValue("@Model", Model);
                    cmd.Parameters.AddWithValue("@Series", Series);
                    cmd.Parameters.AddWithValue("@SIMSlots", SIMSlots);
                    cmd.Parameters.AddWithValue("@CarrierType", CarrierType);
                    cmd.Parameters.AddWithValue("@ReleaseDate", ReleaseDate);
                    cmd.Parameters.AddWithValue("@RAM", RAM);
                    cmd.Parameters.AddWithValue("@RAMMemUnit", RAMMemUnit);
                    cmd.Parameters.AddWithValue("@SecondryMem", SecondryMem);
                    cmd.Parameters.AddWithValue("@SecondMemUnit", SecondMemUnit);
                    cmd.Parameters.AddWithValue("@Expandable", Expandable);
                    cmd.Parameters.AddWithValue("@ExpandableMemUnit", ExpandableMemUnit);
                    cmd.Parameters.AddWithValue("@OSVersion", OSVersion);
                    cmd.Parameters.AddWithValue("@Processor", Processor);
                    cmd.Parameters.AddWithValue("@ScreenSize", ScreenSize);
                    cmd.Parameters.AddWithValue("@ScreenSizeType", ScreenSizeType);
                    cmd.Parameters.AddWithValue("@Battery", Battery);
                    cmd.Parameters.AddWithValue("@BatteryType", BatteryType);
                    cmd.Parameters.AddWithValue("@Comments", Comments);
                    cmd.Parameters.AddWithValue("@SupplierID", SupplierID);
                    cmd.Parameters.AddWithValue("@PurchasePrice", Price);
                    cmd.Parameters.AddWithValue("@PurchasePriceUnit", PriceUnit);
                    cmd.Parameters.AddWithValue("@UnitsInStock", UnitsInStock);
                    cmd.Parameters.AddWithValue("@ProductPhoto", SaveProductPhoto);
                    //Connection
                    conn.Open();
                    //Execution
                    cmd.ExecuteNonQuery();
                }
            }
        }
        public DataTable LoadCategoryComboBox()
        {
            DataTable categoryComboboxValues = new DataTable();

            using (SqlConnection conn = new SqlConnection(connString))
            {
                using (SqlCommand cmd = new SqlCommand("spProducts_GetAllCategories", conn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;

                    conn.Open();
                    SqlDataReader reader = cmd.ExecuteReader();
                    categoryComboboxValues.Load(reader);
                }
            }
            return categoryComboboxValues;
        }
        public DataTable LoadSeriesComboBox()
        {
            DataTable seriesComboBoxValues = new DataTable();

            using(SqlConnection conn = new SqlConnection(connString))
            {
                using(SqlCommand cmd = new SqlCommand("spProducts_GetAllSeries", conn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;

                    conn.Open();
                    SqlDataReader reader = cmd.ExecuteReader();
                    seriesComboBoxValues.Load(reader);
                }
            }
            return seriesComboBoxValues;
        }
        public DataTable LoadSupplierComboBox()
        {
            DataTable supplierComboBoxValues = new DataTable();

            using (SqlConnection conn = new SqlConnection(connString))
            {
                using (SqlCommand cmd = new SqlCommand("spProducts_GetAllSuppliers", conn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;

                    conn.Open();
                    SqlDataReader reader = cmd.ExecuteReader();
                    supplierComboBoxValues.Load(reader);
                }
            }
            return supplierComboBoxValues;
        }
    }
}

存储过程

ALTER Procedure [dbo].[spProducts_InsertProduct]
 @Name          nvarchar(50)
,@CategoryID    int
,@Model         nvarchar(50)
,@Series        nvarchar(50)
,@SIMSlots      int
,@CarrierType   nvarchar(20)
,@ReleaseDate   DateTime = null
,@RAM           int
,@RAMMemUnit    nvarchar(20)
,@SecondryMem   int
,@SecondMemUnit nvarchar(20)
,@Expandable    int
,@ExpandableMemUnit nvarchar(20)
,@OSVersion     nvarchar(50)
,@Processor     nvarchar(50)
,@ScreenSize    nvarchar(50)
,@ScreenSizeType nvarchar(20)
,@Battery       int
,@BatteryType   nvarchar(20)
,@Comments      nvarchar(MAX)
,@SupplierID    int
,@Price         float
,@PriceUnit     nvarchar(20)
,@UnitsInStock  int
,@ProductPhoto  IMAGE
As
Begin

INSERT INTO tblProducts(Name,CategoryID,Model,Series,SIMSlots,CarrierType,ReleaseDate,RAM,RAMMemUnit,SecondryMem,SecondMemUnit,Expandable,ExpandableMemUnit,OSVersion,Processor,ScreenSize,ScreenSizeType,Battery,BatteryType,Comments,SupplierID,Price,PriceUnit, UnitsInStock, Product_Photo)
VALUES(@Name,@CategoryID,@Model,@Series,@SIMSlots,@CarrierType,@ReleaseDate,@RAM,@RAMMemUnit,@SecondryMem,@SecondMemUnit,@Expandable,@ExpandableMemUnit,@OSVersion,@Processor,@ScreenSize,@ScreenSizeType,@Battery,@BatteryType,@Comments,@SupplierID,@Price,@PriceUnit,@UnitsInStock, @ProductPhoto)

End
请帮助我,因为我被困在这里两天了。 谢谢!

1 个答案:

答案 0 :(得分:1)

如果文本框不为空,则此验证有效

if (ExpandableTextBox.Text != "")
{
    int outexpmem;
    if (!int.TryParse(ExpandableTextBox.Text, out outexpmem))
    {
        ValidationMessage(ExpandableTextBox, "Expandable memory can only numbers!");
        return false;
    }
  if (ExpandableMemUnitComboBox.Text.Trim() == "")
    {
        ValidationMessage(ExpandableMemUnitComboBox, "Please select a Memory Unit!");
        return false;
    }
}

但是你得到错误的那一行是在每个案例中尝试Convert.ToInt32(ExpandableTextBox.Text)

如果ExpandableTextBox文本为空,则此行将抛出错误,就像您收到

一样
db.InsertProductInDB(NameTextBox.Text, Convert.ToInt32(CategoryComboBox.SelectedValue), ModelTextBox.Text, SeriesComboBox.Text, Convert.ToInt32(SIMSlotsComboBox.Text), CarrierTypeComboBox.Text, GetReleaseDate(), Convert.ToInt32(RAMTextBox.Text), RAMMemUnitComboBox.Text, Convert.ToInt32(SecondryMemTextBox.Text), SecondMemUnitComboBox.Text, Convert.ToInt32(ExpandableTextBox.Text), ExpandableMemUnitComboBox.Text, OSVersionComboBox.Text, ProcessorComboBox.Text, ScreenSizeTextBox.Text, ScreenSizeTypeComboBox.Text, Convert.ToInt32(BatteryTextBox.Text), BatteryTypeComboBox.Text, CommentsTextBox.Text, Convert.ToInt32(SupplierComboBox.SelectedValue), float.Parse(PriceTextBox.Text), PriceUnitComboBox.Text, Convert.ToInt32(QuantityTextBox.Text), SaveProductPhoto());

您可以针对可选字段Convert.ToInt32(!string.IsNullOrEmpty(ExpandableTextBox.Text)?ExpandableTextBox.Text :"0")

尝试类似的操作