Hjälp med SQLserver och C# i .NET
Jag försöker fixa en add to cart knapp men jag får ett error msg som jag inte vet hur jag kommer runt. Det känns som det är USERID som ska ändras men jag vet inte till vad. några idéer?
min ~aspx.cs ser ut så här.
protected void btnAddtoCart_Click(object sender, EventArgs e)
{
Int64 PID = Convert.ToInt64(Request.QueryString["PID"]);
using (SqlConnection con1 = new SqlConnection(CS))
{
using (SqlCommand cmd = new SqlCommand("select * from tblCart where PID='" + PID + "'", con1))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
Int32 updateQty = Convert.ToInt32(dt.Rows[0][8].ToString());
Int32 UserID = Convert.ToInt32(Session["USERID"].ToString());
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RayOfbDB"].ConnectionString))
{
SqlCommand cmdU = new SqlCommand("UPDATE tblCart SET Qty =@Quantity WHERE PID=@CartPID", con);
cmdU.Parameters.AddWithValue("@Quantity", updateQty + 1);
cmdU.Parameters.AddWithValue("@CartPID", PID);
con.Open();
cmdU.ExecuteNonQuery();
con.Close();
}
}
else
{
Int32 UserID = Convert.ToInt32(Session["USERID"].ToString());
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RayOfbDB"].ConnectionString))
{
string sqlQuery = "insert into tblCart values (@UID,@PID,@PName,@PPrice,@PSelPrice,@Qty)";
SqlCommand myCmd = new SqlCommand(sqlQuery, con);
myCmd.Parameters.AddWithValue("@UID", UserID);
myCmd.Parameters.AddWithValue("@PID", Session["CartPID"].ToString());
myCmd.Parameters.AddWithValue("@PName", Session["myPName"].ToString());
myCmd.Parameters.AddWithValue("@PPrice", Session["myPPrice"].ToString());
myCmd.Parameters.AddWithValue("@PSelPrice", Session["myPSelPrice"].ToString());
myCmd.Parameters.AddWithValue("@Qty", "1");
con.Open();
Int64 CartID = Convert.ToInt64(myCmd.ExecuteScalar());
con.Close();
}
}
}
}
}
}
felmeddelandet jag får är "Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code."
och SQL bordet tblCart ser ut så här.
create table tblCart
(
CartID int primary key identity(1,1),
UID int,
PID int,
PName nvarchar(MAX),
PPrice money,
PSelPrice money,
SubPAmount as PPrice * Qty,
SubSAmount as PSelPrice * Qty,
Qty int,
)