请按照下列步骤操作:
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,请描述一些关于之前的链接填充它。 –