2014-07-18 35 views
-1

我在datagridview中將column checkBox定位爲column0。我想獲得列1檢查列column1的總和行是真的。我用這個代碼:C#在dataGridView中使用checkBox,並獲得檢查列的總和行是真的

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) 
{ 
    double sum = 0; 

    for (int i = 0; i < dataGridView1.Rows.Count; ++i) 
    { 
     if (Convert.ToBoolean(dataGridView1.Rows[i].Cells[0].Value) == true) 
     { 
      sum += double.Parse(dataGridView1.Rows[i].Cells[1].Value.ToString()); 
     } 
    } 

    textBox1.Text = sum.ToString(); 
} 

但它不能正常工作。

+0

你說的「不正常」呢?它是WinForm嗎? – Habib

+0

是的。它是WinForm。 textBox1的值對於每個事件都是變化的。 – user3812553

回答

1

如何像這樣

textBox1.Text = (dataGridView1.Rows.Cast<DataGridViewRow>() 
     .Where(r => Convert.ToBoolean(r.Cells[0].Value).Equals(true)) 
     .Sum(t => Convert.ToInt32(t.Cells[1].Value))).ToString(); 
+0

此代碼在下次運行後生效。我可以在另一個dataGridView事件中使用我的代碼嗎? – user3812553

+0

是的只是爲它創建一個方法,並調用你想觸發它的所有事件的方法。 – Tsukasa

1

在C#中的DataGridView選中該複選框列的所有複選框:

 for (int i = 0; i < dataGridView1.Rows.Count; ++i) 
     { 
      dataGridView1.Rows[i].Cells[0].Value = true; 
     } 
相關問題