从列表框中的数据库添加产品后,如何避免重复的商品?

时间:2019-01-28 10:59:54

标签: c# asp.net listbox

我一直在寻找解决方案,但似乎没有用。我试图从我的数据库产品中添加一个产品,然后将其放在“购买”数据库中。另一方面,当我按产品1添加到购物车按钮时,它将出现在我的列表框中。当我第二次按添加到购物车按钮时,它将显示“重复项”消息。我尝试了很多代码,但是一直在增加和增加。这是我下面的代码。一开始,我的列表框将为空,因此当我按或我的用户按“添加到购物车”按钮时,它将出现在包含重复项功能的列表框中。希望能得到一些帮助。将不胜感激。谢谢!

 string uname = Convert.ToString(Session["username"]);
    int memberid = Convert.ToInt32(Session["memberID"]);
    SqlConnection connAdd1 = new SqlConnection("Server=localhost; Database = WeFootball; Integrated Security=SSPI");
    SqlCommand prod = new SqlCommand("Select * from purchases", connAdd1);
    connAdd1.Open();

    SqlDataReader dr;
    dr = prod.ExecuteReader();
    while (dr.Read())
    {
        ListItem meow = new ListItem(product1);
        if (cartlist.Items.Contains(meow))
        {

            ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Duplicate item detected!');window.location ='Products.aspx';", true);
        }
        else
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Added to cart!');window.location ='Products.aspx';", true);
        }
    }

    dr.Close();
    connAdd1.Close();


    if (cartlist.Items.Count == 0)
    {

        SqlConnection connAdd2 = new SqlConnection("Server=localhost; Database = WeFootball; Integrated Security=SSPI");
        //string uname = Convert.ToString(Session["username"]);
        //int memberid = Convert.ToInt32(Session["memberID"]);
        connAdd2.Open();
        SqlCommand cmd = connAdd2.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "insert into purchases(member_name,product_name,quantity,purchase_by,product_id,member_id) values('" + uname + "','" + product1 + "','" + 1 + "','" + uname + "','" + 1 + "','" + memberid + "')";

        cmd.ExecuteNonQuery();
        connAdd2.Close();

        BindData();
    }

0 个答案:

没有答案