求大神帮忙解决;我想要实现“点击加入购物车”,然后就将datalist中显示的图书和用户添加到数据库,并在另一界面显示购物车,加入购物车的按钮的源代码是这样的:编译没错,调试就出现“未将对象引用设置到对象的实例。”菜鸟级找不到解决方法了。
protected void Button1_Click2(object sender, EventArgs e)
{
if (Session["name"] == null)
{
Response.Redirect("index.aspx");
}
else
{
string connectionString = "server=.; DataBase=BookStore; Integrated Security=SSPI;";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
try
{
foreach (DataListItem item in DataList2.Items)
{
int Bamount = int.Parse(Request.QueryString["Tnventory"].ToString());
int CBamount = int.Parse(this.camount.Text.Trim().ToString());
string username = Session["name"].ToString();
string bookid = Request.QueryString["bookid"].ToString();
string BookName = Request.QueryString["BookName"].ToString();
float Price = float.Parse(Request.QueryString["Price"].ToString());
int Cnum = 0;
string select = "select Cname from car where Cname=@UserName";
SqlCommand cmd = new SqlCommand(select, conn);
cmd.Parameters.Add("@UserName", SqlDbType.VarChar, 10);
cmd.Parameters["@UserName"].Value = username;
SqlDataReader sdr;
sdr = cmd.ExecuteReader();
int o = 0;
SqlCommand cd;
while (sdr.Read())
{
o = 1;
sdr.Close();
string sql = "select MAX(Cnum) from car where Cname='" + username + "' ";
cd = new SqlCommand(sql, conn);
string str = cd.ExecuteScalar().ToString();
int h = int.Parse(str);
Cnum = h + 1;
break;
}
if (o == 0)
{
sdr.Close();
Cnum = 1;
}
if (Bamount < CBamount)
{
Response.Write("<script type=\"text/javascript\">alert(\"库存不足!\");</script>");
}
else
{
float Cprice = Price * CBamount;
string sql1 = "insert into car(Cname,Cnum,bookid,BookName,Price,CBamount,Cprice) values('" + username + "','" + bookid + "','" + BookName + "','" + Price + "','" + CBamount + "','" + Cprice + "')";
SqlCommand cmd1 = new SqlCommand(sql1, conn);
cmd1.ExecuteNonQuery();
Response.Write("<script type=\"text/javascript\">alert(\"已经加入购物车!\");</script>");
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
}
}
}