2016-05-29 74 views
0

我的表是这样的:如何计算datagridview中每个项目的小计?

NAME ITEM COUNT 
a  x  2 
a  y  1 
b  x  3 
c  z  1 
d  y  1 
d  y  1 

我已经使用这个代码来计算总

double sum = 0; 
for (int i = 0; i < dataGridView1.Rows.Count; ++i) 
    { 
     sum += Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value); 
    } 

如何计算总和分别每一个项目,结果应该是:

x=5 
y=3 
z=1 
+2

您是否在寻找一个C#解决方案或SQL一个?如果这是一个Sql解决方案,那么您正在使用哪个数据库? –

+0

http://stackoverflow.com/questions/18417333/how-we-add-numaric-value-of-multiple-cell-of-a-datagridview/18418027#18418027 – SK2185

+0

@Senthilkumar,请描述一些关于之前的链接填充它。 –

回答

0

请按照下列步骤操作:

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 
    }  

希望这可以帮助你。

+0

'Z'列呢? –

+0

那么,如果'ITEM'列中有更多的案例呢?我想你应该使用'group by'。 –

+0

@SiyavashHamdi我已经发布了一个基于OP提供的确切用例的答案。现在你所说的是更实际的场景,是的,群组和数据必须应用于数据源级别。 –

0

尝试下面的方法来获取分组项目与求和的字典:

private Dictionary<string, int> GetSummation() 
{ 
    var kvp = new List<KeyValuePair<string, int>>(); 

    for (var i = 0; i < GridView1.Rows.Count; i++) 
    { 
     var item = GridView1.Rows[i].Cells[1].Text.Trim(); 
     var count = Convert.ToInt32(GridView1.Rows[i].Cells[2].Text); 

     kvp.Add(new KeyValuePair<string, int>(item, count)); 
    } 

    return kvp.GroupBy(k => k.Key).ToDictionary(g => g.Key, g => g.Sum(x => x.Value)); 
}