首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何对datagridview中具有相同id的列值求和

问如何对datagridview中具有相同id的列值求和
EN

Stack Overflow用户
提问于 2017-04-22 21:21:49
回答 1查看 860关注 0票数 0

我想计算具有相同id的datagridview中的列值...

请看这里的图片。To view image click here

我写了以下代码..。但是它在datagridview中存储单独的行...

代码语言:javascript
复制
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()); 
        }
}

我希望将值存储在数据库中,如以下输出所示

ID数量J0001 4 J0002 9

请支持我。

EN

回答 1

Stack Overflow用户

发布于 2017-04-22 22:29:48

我不确定发布的代码的总和是什么。但是,一种简单的求和方法,如您所描述的,可以使用Dictionary的string表示“JewelID”,使用int表示数量的总和。循环遍历DataGridView中的行,从“JewelID”列和“quantity”列获得值,并将它们添加到Dictionary中。

如果字典中已存在“数量”,则将“JewelID”值与当前现有值相加,以获得该“JewelID”的“数量”的运行总和。在代码迭代所有行之后,Dictionary将输出到窗体上的一个多行文本框。

代码语言:javascript
复制
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();
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43559734

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档