請按照下列步驟操作:
1)通過數據網格。
2)在循環中標識類似的項目(如x,y和z)並對其進行求和。
int SumX=0;
int SumY=0;
int SumZ=0;
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
if(Convert.ToString(dataGridView1.Rows[i].Cells[1].Value == "x")
sumX += Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value);
else if(Convert.ToString(dataGridView1.Rows[i].Cells[1].Value == "y")
sumY += Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value);
else if(Convert.ToString(dataGridView1.Rows[i].Cells[1].Value == "z")
sumZ += Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value);
}
這裏是一個example。
使用LINQ查詢它非常簡單。
int SumX = dataGridView1.Rows.Cast<DataGridViewRow>()
.Where(r=> Convert.ToInt32(r.Cells["Item"].Value) == "x")
.Sum(t=> Convert.ToInt32(t.Cells["Count"].Value));
編輯
如果你真的想使這個總和的動態,那麼你可以這樣做this.Basically這裏是跟蹤同一項目(S)的再總結相應的字典計數。
Dictionary<string, int> dic = new Dictionary<string, int>();
string item = null;
for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++)
{
item = dataGridView1.Rows[i].Cells[1].Value.ToString();
if (!dic.ContainsKey(item))
{
dic.Add(item, Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value);
}
else
{
dic[item] += Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value);
}
}
現在,您可以遍歷字典並獲取唯一的項目數。
foreach (KeyValuePair<string, int> keyvalue in dic)
{
//get it here
}
希望這可以幫助你。
您是否在尋找一個C#解決方案或SQL一個?如果這是一個Sql解決方案,那麼您正在使用哪個數據庫? –
http://stackoverflow.com/questions/18417333/how-we-add-numaric-value-of-multiple-cell-of-a-datagridview/18418027#18418027 – SK2185
@Senthilkumar,請描述一些關於之前的鏈接填充它。 –