我想用相同的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 QUANTITY J0001 4 J0002 9
请支持我......
答案 0 :(得分:1)
我不确定所发布的代码是什么。但是,您可以使用Dictionary
string
为“JewelID”和int
来保存数量总和,这可以通过一种简单的方法对所描述的总数求和。循环遍历DataGridView
中的行,并从“JewelID”列和“数量”列中获取值,并将其添加到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();
}