错误:输入字符串格式不正确 - ASP.Net

时间:2016-02-07 18:41:08

标签: asp.net sql-server exception formatexception

对此错误消息进行排序的一些帮助将非常感激。在填充页面后单击提交按钮时会触发错误消息。

AddNewProduct

  public partial class AddNewProduct : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GetCategories();
        }
    }

    private void GetCategories()
    {
        ShoppingCart k = new ShoppingCart();
        DataTable dt = k.GetCategories();
        if (dt.Rows.Count > 0)
        {
            ddlProductCategory.DataValueField = "CategoryID";
            ddlProductCategory.DataValueField = "CategoryName";
            ddlProductCategory.DataSource = dt;
            ddlProductCategory.DataBind();
        }
    }

protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (UploadProductPhoto.PostedFile != null)
        {
            SaveProductPhoto();

            ShoppingCart k = new ShoppingCart()
            {
                ProductName = txtProductName.Text,
                CategoryID = Convert.ToInt32(ddlProductCategory.SelectedValue),
                ProductDescription = txtProductDescription.Text,
                ProductPrice = txtProductPrice.Text,
                ProductStock = txtProductStock.Text,
                ProductImageUrl = string.Format("/ProductImages/{0}", UploadProductPhoto.FileName)
              };
            k.AddProduct();
            ClearText();
            Response.Redirect("~/Admin/AdminFillerPage.aspx");
        }
    }
    private void ClearText()
    {
        txtProductName.Text = string.Empty;
        txtProductDescription.Text = string.Empty;
        txtProductPrice.Text = string.Empty;
        txtProductStock.Text = string.Empty;
        UploadProductPhoto = null;
    }
    private void SaveProductPhoto()
    {
        if (UploadProductPhoto.PostedFile != null)
        {
            string fileName = UploadProductPhoto.PostedFile.FileName.ToString();
            string fileExtension = System.IO.Path.GetExtension(UploadProductPhoto.FileName);


            //check file name legnth
            if (fileName.Length > 96)
            {
                //Alert.Show("image name should not exceed 96 characters !");
            }
            //check filetype 
            else if (fileExtension != ".jpeg" && fileExtension != ".jpg" && fileExtension != ".png" && fileExtension != ".bmp")
            {
                //Alert.Show("Only jpeg,jpg,bmp & png imags are allowed!");
            }

            //check file size
            else if (UploadProductPhoto.PostedFile.ContentLength > 4000000)
            {
                //Alert.Show("image size should not be greater than 4MB !");
            }
            //Save images into Images folder
            else
            {
                UploadProductPhoto.SaveAs(System.IO.Path.Combine(Server.MapPath("~/ProductImages/"), fileName));

            }
        }
    }

购物车

public class ShoppingCart
{
    //Declaring Variables
    public int CategoryID;
    public string CategoryName;

    public string ProductName;
    public string ProductDescription;
    public string ProductPrice;
    public string ProductStock;
    public string ProductImageUrl;


    public void AddCategory()
    {
        SqlParameter[] parameters = new SqlParameter[1];
        parameters[0] = DataAccess.AddParamater("@CategoryName", CategoryName, System.Data.SqlDbType.VarChar, 200);
        DataTable dt = DataAccess.ExecuteDTByProcedure("mj350.AddCategory", parameters);
    }

    public void AddProduct()
    {
        SqlParameter[] parameters = new SqlParameter[6];
        //Passing all the parameters that needed to be saved into the database
        parameters[0] = DataLayer.DataAccess.AddParamater("@ProductName", ProductName, System.Data.SqlDbType.VarChar, 500);
        parameters[1] = DataLayer.DataAccess.AddParamater("@CategoryID", CategoryID, System.Data.SqlDbType.Int, 100);
        parameters[2] = DataLayer.DataAccess.AddParamater("@ProductDescription", ProductDescription, System.Data.SqlDbType.VarChar, 800);
        parameters[3] = DataLayer.DataAccess.AddParamater("@ProductPrice", ProductPrice, System.Data.SqlDbType.VarChar, 500);
        parameters[4] = DataLayer.DataAccess.AddParamater("@ProductStock", ProductStock, System.Data.SqlDbType.VarChar, 500);
        parameters[5] = DataLayer.DataAccess.AddParamater("@ProductImage", ProductImageUrl, System.Data.SqlDbType.VarChar, 500);

        //Executes the saved procedure that is saved in the database
        DataTable dt = DataLayer.DataAccess.ExecuteDTByProcedure("mj350.AddProduct", parameters);
    }

存储过程 - 添加产品

CREATE PROCEDURE [AddProduct]
(
@ProductName varchar(500),
@CategoryID  int,
@ProductDescription  varchar(800),
@ProductPrice varchar(500),
@ProductStock varchar(500),
@ProductImage varchar(500)
)

AS
  BEGIN

  BEGIN TRY

    INSERT INTO Product VALUES
     (
     @ProductName,
     @CategoryID,
     @ProductDescription,
             @ProductPrice,
     @ProductStock,
             @ProductImage
     )

  END TRY

  BEGIN CATCH
      --      INSERT INTO dbo.ErrorLog 
      --VALUES(ERROR_MESSAGE(),'sp_GetAllData')
      PRINT( 'Error occured' )
  END CATCH
  END

存储过程 - 获取类别

CREATE PROCEDURE [mj350].[ListCategories]

AS
    BEGIN

    BEGIN TRY

    SELECT * FROM Category

END TRY

BEGIN CATCH
    -- INSRET INTO dbo.ErrorLog
    -- VALYES(ERROR_MESSAGE(), 'SP_GetAllData')
    PRINT( 'Data Insert Error - Please review' )
END CATCH
END

对不起,如果这是一个愚蠢的错误 - 编码技巧不是最好的。感谢所有的帮助。

由于 千斤顶

Example of data form is populated with& Where error message is triggered in code

1 个答案:

答案 0 :(得分:1)

由于以下代码

,您出现此错误
private void GetCategories()
{
    ShoppingCart k = new ShoppingCart();
    DataTable dt = k.GetCategories();
    if (dt.Rows.Count > 0)
    {
        ddlProductCategory.DataValueField = "CategoryID";
        ddlProductCategory.DataValueField = "CategoryName"; // Here you overwrite the DataValueField.
        ddlProductCategory.DataSource = dt;
        ddlProductCategory.DataBind();
    }
}

您使用DataValueField属性名称覆盖CategoryName。然后,当您提交表单时,您正在执行以下代码:

ShoppingCart k = new ShoppingCart()
{
      ProductName = txtProductName.Text,
      CategoryID = Convert.ToInt32(ddlProductCategory.SelectedValue), // Here SelectedValue is in incorrect format.
      ProductDescription = txtProductDescription.Text,
      ProductPrice = txtProductPrice.Text,
      ProductStock = txtProductStock.Text,
      ProductImageUrl = string.Format("/ProductImages/{0}", UploadProductPhoto.FileName)
};

由于此行CategoryID = Convert.ToInt32(ddlProductCategory.SelectedValue)而引发异常。发布的选定值格式不正确,因为您将下拉列表的值与类别名称绑定。

要解决此问题,您必须在此行ddlProductCategory.DataValueField = "CategoryName";

中替换GetCategories中的此行ddlProductCategory.DataTextField = "CategoryName";