1

Some assistance with sorting this error message would be gratefully appropriated. The error message is triggered when clicking on the submit button after populating the page.

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

            }
        }
    }

Shopping Cart

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

Stored Procedure - Add Product

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

Stored Procedure - Get Categories

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

Sorry if it's a silly mistake - coding skills not the best. All help gratefully received.

Thanks Jack

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

2
  • 2
    It seems that ddlProductCategory.SelectedValue return an empty string or null. Make sure that ddlProductCategory.SelectedValue isn't empty. Check the HTML source and check if otpiotn value are correctly setted. Commented Feb 7, 2016 at 18:44
  • @CodeNotFound. The ddl categories is populated from the DB using a stored procedure. I have added the code - does this help with the troubleshooting? I don't really understand your above comment (sorry :() Commented Feb 7, 2016 at 18:58

1 Answer 1

1

You have this error because of the following 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();
    }
}

You overwrite the DataValueField with CategoryName property name. Then when you submit your form you are executing the following code :

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

The exception is thrown because of this line CategoryID = Convert.ToInt32(ddlProductCategory.SelectedValue). The posted Selected value is not in correct format because you bind the value of your dropdown list with the name of the category.

To solve this you must replace this line ddlProductCategory.DataValueField = "CategoryName"; in your GetCategories by this line ddlProductCategory.DataTextField = "CategoryName";

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you SO much for all of your help this afternoon! You are an absolute lifesaver! I am sure I will be back soon having made more silly typo's hehe! Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.