检查库存(如果存在)

时间:2015-10-04 13:35:36

标签: c# asp.net

我想检查数据库中是否存在productID,如果productID不存在则不允许更新

这是我用来检查的代码

 bool HasInventory()
{
    foreach (ListViewItem item in lvMaterialsList.Items)
    {

        Label ltr = (Label)item.FindControl("Label1");

        string name = ltr.Text;
        bool existing = true;
        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "SELECT ProductID FROM Inventory WHERE ProductID=" + name;
        cmd.Parameters.AddWithValue("@ProductID", name);
        SqlDataReader data = cmd.ExecuteReader();
        if (data.HasRows)
            existing = true;
        else
            existing = false;
        con.Close();

        return existing;

    }
    return false;
}

这是用于更新数据库的按钮的代码

 protected void lvMaterialsList_ItemCommand(object sender, ListViewCommandEventArgs e)
{
    bool existingSupply = IsExisting();
    bool hasquantity = HasInventory();

    Label ltRefNo = (Label)e.Item.FindControl("ltRefNo");
    Label Label1 = (Label)e.Item.FindControl("Label1");
    TextBox txtAlloted = (TextBox)e.Item.FindControl("txtAlloted");
    Literal ltUsed = (Literal)e.Item.FindControl("ltUsed");

    int alloted = Convert.ToInt32(txtAlloted.Text);
    int productid = Convert.ToInt32(Label1.Text);

    if (e.CommandName == "updateused")
    {
        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;

        if (existingSupply && hasquantity)
        {
            cmd.CommandText = "UPDATE RequiredMaterials SET Used=Used + @Used WHERE ReqMatID=@ReqMatID";

        }
       else 
        {
            cmd.CommandText = "UPDATE RequiredMaterials SET Used=@Used WHERE ReqMatID=@ReqMatID";
        }

        cmd.Parameters.AddWithValue("@Used", alloted);
        cmd.Parameters.AddWithValue("@ReqMatID", ltRefNo.Text);                      
        cmd.ExecuteNonQuery();

        cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "UPDATE Inventory SET Quantity = Quantity - @Quantity " +
            "WHERE ProductID=@ProductID";
        cmd.Parameters.AddWithValue("@Quantity", alloted);
        cmd.Parameters.AddWithValue("@ProductID", productid);
        cmd.ExecuteNonQuery();
        con.Close();


    }

    GetMaterialsList();

}

我不知道为什么会继续更新..

0 个答案:

没有答案
相关问题