2017-03-06 34 views
1

我試圖計算datagridview中名爲QTY的列的總數。 但我不知道。我的代碼如下。請問你能幫幫我嗎? enter image description hereDatagridview列總數

public int RowCount { get; set; } 

    [BrowsableAttribute(false)] 
    private void dataGridView1_SelectionChanged(object sender, EventArgs e) 

    { 

    private void UpdateLabelText() 
    { 
     int QtyTotal = 0; 

     int counter; 

     // Iterate through all the rows and sum up the appropriate columns. 
     for (counter = 0; counter < (dataGridView1.Rows.Count); 
      counter++) 
     { 
      if (dataGridView1.Rows[counter].Cells["Qty"].Value 
       != null) 
      { 
       if (dataGridView1.Rows[counter]. 
        Cells["Qty"].Value.ToString().Length != 0) 
       { 
        QtyTotal += int.Parse(dataGridView1.Rows[counter]. 
         Cells["Qty"].Value.ToString()); 
       } 
      } 
     } 

     // Set the labels to reflect the current state of the DataGridView. 
     label17.Text = "Qty Total: " + QtyTotal.ToString(); 

    } 
+0

什麼是與代碼的問題?異常,意外的結果? – Pikoh

+0

總共未顯示標籤17 – Bahadir

+0

它給出了預期錯誤 – Bahadir

回答

1

試試這個:

int sum = 0; 
int col_index=YOUR_COLUMN_INDEX; 
for (int i = 0; i < dataGridView1.Rows.Count; ++i) 
{ 
    sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[col_index].Value); 
} 
label17.Text= sum.ToString(); 
+0

由於它的工作 – Bahadir

+0

歡迎您 – imsome1

+0

如果這有效,請接受爲已接受的答案 – imsome1

0

試試這個

foreach (DataGridViewRow item in dataGridView2.Rows) 
{ 
    int n = item.Index; 
    text_tot.Text = (int.Parse(label17.Text) + int.Parse(dataGridView1.Rows[n].Cells[(index)].Value.ToString())).ToString(); 
}