Error: Input string was not in a correct format - ASP.Net

Error: Input string was not in a correct format - ASP.Net

如果能提供一些对此错误消息进行排序的帮助,我们将不胜感激。填充页面后单击提交按钮时会触发错误消息。

添加新产品

  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

您出现此错误是因为以下代码

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

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

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)而抛出异常。发布的选定值格式不正确,因为您将下拉列表的值与类别名称绑定。

要解决此问题,您必须将 GetCategories 中的 ddlProductCategory.DataValueField = "CategoryName"; 行替换为 ddlProductCategory.DataTextField = "CategoryName";