简体   繁体   中英

how to sum the column values with same id in datagridview

I want to calculate the column values in datagridview with same id ...

Kindly see the image here... To view image click here

I wrote the following code... but it stores individual rows what in datagridview....

private void AddStockTable()
{
        try
        {
            Sqlcon = objDB.DBConnection();
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                Query = "insert into tblStock (PurchaseId, CurDate,JewelID, Purity, Weight, Quantity, SupplierId,G916,G22ct,G90,Silver) values " +
                    " ('" + txtPurchaseId.Text + "','" + dateTimePicker1.Text + "','" + dataGridView1[0, i].Value.ToString() + "','" + dataGridView1[2, i].Value.ToString() + "' " +
                    ", '" + lblTotalWeight.Text + "','" + lblQuantity.Text + "','" + lblSupplier.Text + "','" + lbl916.Text + "','" + lbl22.Text + "','" + lbl90.Text + "','" + lblSilver.Text + "') ";

                Sqlcmd = new SqlCommand(Query, Sqlcon);
                Sqlcmd.ExecuteNonQuery();    
            }
        }
        catch (Exception ex)
        { 
             MessageBox.Show(ex.ToString()); 
        }
}

I want to store the values in database like the following output

ID QUANTITY J0001 4 J0002 9

Kindly support me...

I am not sure what the posted code is summing. However, one simplistic approach to sum the totals as you describe could be done with a Dictionary of string for “JewelID” and an int to keep a sum of the quantity. Loop through the rows in the DataGridView and get the values from the “JewelID” column and the “quantity” column and add them to the Dictionary .

If a “JewelID” already exist In the dictionary, then the “quantity” value is added to the currently existing value to get a running total of the “Quantity” for that “JewelID”. After the code iterates through all the rows, the Dictionary is output to a multi-line text box on the form.

private void btnUpdateIDQty_Click(object sender, EventArgs e) {
  Dictionary<string, int> IDCount = new Dictionary<string, int>();
  string curId = "";
  int curQty = 0;
  int oldValue;
  foreach (DataGridViewRow row in dgvPurchaseOrder.Rows) {
    if (row.Cells["JewelID"].Value != null && row.Cells["Quantity"].Value != null) {
      curId = row.Cells["JewelID"].Value.ToString();
      int.TryParse(row.Cells["Quantity"].Value.ToString(), out curQty);
      if (IDCount.ContainsKey(curId)) {
        IDCount.TryGetValue(curId, out oldValue);
        curQty += oldValue;
        IDCount[curId] = curQty;
      }
      else {
        IDCount.Add(curId, curQty);
      }
    }
    else {
      // one of the cells is null ignore
    }
  }

  StringBuilder sb = new StringBuilder();
  sb.Append("ID quantity totals" + Environment.NewLine);
  foreach (KeyValuePair<string, int> pair in IDCount) {
    sb.Append("JewelryID: " + pair.Key + " Total Qty: " + pair.Value + Environment.NewLine);
  }
  txtIDQuantity.Text = sb.ToString();
}

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