简体   繁体   中英

How to implement fifo with conditions in C# and SQL Server?

I have selected multiple datarows with same product name, price and quantity and sorted them according to their primary key values in datatable. But when I decrease stock quantity, it decreases from all the rows. I want my code to check stock quantity according to user quantity entered in textbox and decrease it from FIRST ROW ONLY. This is what I have been able to do so far. apologies in advance for bad formatting I am new to programming and stackoverflow.

The data table has columns

Item_Name, Item_Quantity, Item_Price.

Code:

private void btn_save_Click(object sender, EventArgs e)
{
    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "select * from stock_recieve where Item_Name like'" + comboBoxitem.Text + "'order by [Bill No] asc";

    cmd.ExecuteNonQuery();

    DataTable dt = new DataTable();
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Fill(dt);

    foreach (DataRow dr in dt.Rows)
    {
        // DataRow row = dt.Select("Item_Quantity").FirstOrDefault();
        dt.Rows[0]["Item_Quantity"]=;

        int qty = 0;
        string pname = "";

        qty = Convert.ToInt32(dr["Item_Quantity"].ToString());
        qty = Convert.ToInt32(textBoxqty.Text);

        pname = dr["Item_Name"].ToString();

        SqlCommand cmd6 = con.CreateCommand();
        cmd6.CommandType = CommandType.Text;
        cmd6.CommandText = "update stock_recieve set Item_Quantity=Item_Quantity-" + qty + "where Item_Name ='" + pname.ToString() + "'";

        cmd6.ExecuteNonQuery();
    }

    //MessageBox.Show("Record inserted successfully");
}

Just use top 1 on your select query . Also using SQL parameters is very important. Try like:

...
cmd.CommandText = "select TOP 1 * from stock_recieve where Item_Name like @name order by [Bill No] asc";
cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value =comboBoxitem.Text;
cmd.ExecuteNonQuery();
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM