我想计算具有相同id的datagridview中的列值...
请看这里的图片。To view image click here
我写了以下代码..。但是它在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());
}
}我希望将值存储在数据库中,如以下输出所示
ID数量J0001 4 J0002 9
请支持我。
发布于 2017-04-22 22:29:48
我不确定发布的代码的总和是什么。但是,一种简单的求和方法,如您所描述的,可以使用Dictionary的string表示“JewelID”,使用int表示数量的总和。循环遍历DataGridView中的行,从“JewelID”列和“quantity”列获得值,并将它们添加到Dictionary中。
如果字典中已存在“数量”,则将“JewelID”值与当前现有值相加,以获得该“JewelID”的“数量”的运行总和。在代码迭代所有行之后,Dictionary将输出到窗体上的一个多行文本框。
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();
}https://stackoverflow.com/questions/43559734
复制相似问题