Qty Control in C#

后端 未结 5 961
-上瘾入骨i
-上瘾入骨i 2021-01-27 07:50

pstrjds, From the code you have provided I am trying to implement that code and the msdn link you provided couple of days ago. I am not sure how to put it together but I am see

5条回答
  •  盖世英雄少女心
    2021-01-27 08:22

    After reading your question again, I am more convinced that the comment I posted is actually the problem. You said in your question that your quantity is not going down. If you look at the return value from the line:

    cmd.ExecuteNonQuery();
    

    in your else statement I believe you will get a value of 0. This indicates that no records where updated. I believe the problem is exactly related to your query. If you connect to your database with a utility such as LINQPad or the Sql Management studio and run the query you have listed in your code I think you will find it is not updating anything. I highly suspect that your inventory is not being stored in a table called tblContacts. Which is why you can't select a quantity from it nor update a quantity in it.

    Edit: Meant to mention this initially and then got sidetracked and forgot to add it. I would put your SqlCommand in a using statement. The SqlCommand object is disposable and so it is good practice to place disposable objects in a using statement or in some sort of try/finally pattern where they can be cleaned up.

    Additional edit - restructuring your code:

        cs.Open();
        int remainingStock = 0;
        string Query = "SELECT QTY from tblInventory WHERE ID=19";
        using(SqlCommand cmd = new SqlCommand(Query, cs))
        {
            var result = cmd.ExecuteScaler();
            if (result != null)
            {
                string str = result.ToString();
                if (!string.isNullOrWhiteSpace(str))
                {
                    // NOTE: It would probably be safer to use int.TryParse here
                    remainingStock = Convert.ToInt32(cmd);
                }
    
                if (remainingStock == 0)
                {
                    lbqty.Text = "Not enough stocks.";
                }
                else
                {
                    cmd.CommandText = "UPDATE tblInventory SET QTY = QTY-1 WHERE ID=19";
                    int rowsUpdated = cmd.ExecuteNonQuery();
                    remainingStock--;
    
                    if (remainingStock == 1)
                    {
                        lbqty.Text = "Re-order. Remaining stocks: 1";
                    }
                    else
                    {
                        string remaining = "Remaining stocks: " + remainingCount.ToString();
                        txtQty.Text = remaining;
                        lbqty.Text = remaining;
                    }
                }
            }
            else
                lbqty.Text = "No stock for contact";
            }
    
            dgUpdate();
        }
        cs.Close();
    

提交回复
热议问题