2016-05-29 268 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)); 
}