简体   繁体   中英

Trying to build a “add to cart” button connected to SQLserver

I'm trying to make a add to cart button in my ProductView.aspx. When user browse the Products and click on them there will be an add to cart button next to a picture. Every information about the product are stored in SQL with the name 'tblProducts'. The user will choose a size and then press "Add to cart". I have made two new tables in SQL named 'tblCart' and 'tblPurchase' where the items will be added. The error that appears is

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

and it complains about this line of code

Int32 UserID = Convert.ToInt32(Session["USERID"].ToString());

I know the its empty and I don't seem to make SQL to understand that I want to add data to the tblCart... Here is the full code for the add button.

protected void btnAddtoCart_Click(object sender, EventArgs e)
    {
        Int64 PID = Convert.ToInt64(Request.QueryString["PID"]);
        using (SqlConnection con = new SqlConnection(CS))
        {
            using (SqlCommand cmd = new SqlCommand("select * from tblCart where PID='" + PID + "'", con))
            
            {

                cmd.CommandType = CommandType.Text;
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    if (dt.Rows.Count > 0)
                    {
                        Int64 updateQty = Convert.ToInt64(dt.Rows[0][8].ToString());
                        Int64 UserID = 0;
                        Int64.TryParse((String)Session["Username"], out UserID);
                        using (SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["RayOfbDB"].ConnectionString))
                        {

                            SqlCommand cmd1 = new SqlCommand("UPDATE tblCart SET Qty=@Quantity WHERE PID=@CartPID", con1);
                            cmd1.Connection = con1;
                            cmd1.Parameters.Add("@Quantity", SqlDbType.Int).Value = updateQty + 1;
                            cmd1.Parameters.Add("@CartPID", SqlDbType.Int).Value = PID;
                            con1.Open();
                            cmd1.ExecuteNonQuery();                                
                        }
                    }
                    else
                    {
                        Int64 UserID = 0; 
                        Int64.TryParse((String)Session["Username"], out UserID);
                        using (SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["RayOfbDB"].ConnectionString))
                        {
                            string sqlQuery = "insert into tblCart values (@UID,@PID,@PName,@PPrice,@PSelPrice,@Qty)";
                            SqlCommand Cmd2 = new SqlCommand(sqlQuery, con2);
                            Cmd2.Connection = con2;
                            Cmd2.Parameters.Add("@UID", SqlDbType.Int).Value = UserID;
                            Cmd2.Parameters.Add("@PID", SqlDbType.Int).Value = CartPID;
                            Cmd2.Parameters.Add("@PName", SqlDbType.NVarChar, -1).Value = myPName;
                            Cmd2.Parameters.Add("@PPrice", SqlDbType.Money).Value = myPPrice;
                            Cmd2.Parameters.Add("@PSelPrice", SqlDbType.Money).Value = myPSelPrice;
                            Cmd2.Parameters.Add("@Qty", SqlDbType.Int).Value = "1";
                            con.Open();
                            Int64 CartID = Convert.ToInt64(Cmd2.ExecuteScalar());
                            
                        }
                    }
                }
            }
        }
    }

PselPrice, myPselPrice etc is a misspelling that I use also in SQL. So its misspelled everywhere.

EDIT: I updated the code to cmd.Parameter.Add instead and can now see the values PName PPrice etc doesn't have any contact. Any suggestions how to fix that? 在此处输入图像描述

When Session["USERID"] is null you will have this problem of System.NullReferenceException because you are trying to convert a null value to string and after that to Int32.

So I think you must verify if Session["USERID"] is not null before doing that. Try to debug this session variable to verify if it has some value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM