2012-03-28 73 views
0

我需要使用checkbox_checkChanged事件同時在我的C#應用​​程序的datagridview中勾選多個複選框,當他們使用鼠標先高亮顯示他們需要的細胞。 因此,基本上最終用戶將使用鼠標突出顯示datagridview中的單元格,然後單擊複選框2,然後在複選框中勾選它們突出顯示單元格的每一行中的複選框。如何使用C#在datagridview中檢查多個複選框

這是我的代碼,它顯示一個窗口,指出已選擇多少行/單元格。然後我需要在datagridview中的每個複選框中打勾,在該行中具有突出顯示的單元格。目前它將顯示窗口記錄哪些行/單元格已被選中,然後當單擊確定按鈕時,它將勾選datagridview中的每個複選框,而不是僅在該行中具有突出顯示的單元格的複選框。

private void checkBox2_CheckedChanged(object sender, EventArgs e) 
    { 
     Int32 selectedCellCount = dgv2.GetCellCount(DataGridViewElementStates.Selected); 
     if (selectedCellCount > 0) 
     { 
      if (dgv2.AreAllCellsSelected(true)) 
      { 
       MessageBox.Show("All cells are selected", "Selected Cells"); 
      } 

      else 
      { 
       System.Text.StringBuilder sb = new System.Text.StringBuilder(); 

       for (int i = 0; 
        i < selectedCellCount; i++) 
       { 
        sb.Append("Row: "); 
        sb.Append(dgv2.SelectedCells[i].RowIndex.ToString()); 
        sb.Append(", Column: "); 
        sb.Append(dgv2.SelectedCells[i].ColumnIndex.ToString()); 
        sb.Append(Environment.NewLine); 
       } 


       sb.Append("Total: " + selectedCellCount.ToString()); 
       // confirmation 
       MessageBox.Show(sb.ToString(), "Selected Cells"); 

       foreach (DataGridViewRow row in dgv2.Rows) 
       { 
        row.Cells[2].Value = checkBox2.Checked && String.IsNullOrEmpty(row.Cells[0].ErrorText); 
       } 

      } 
     } 
    } 

請幫助...

回答

0

我看到你的代碼是從這裏:http://msdn.microsoft.com/en-us/library/x8x9zk5a.aspx但不是這樣的:

foreach (DataGridViewRow row in dgv2.Rows) 
{ 
    row.Cells[2].Value = checkBox2.Checked && String.IsNullOrEmpty(row.Cells[0].ErrorText); 
} 

您需要按照文章所說的話,在這裏這將指向你在正確的方向:

for (int i = 0; i < selectedCellCount; i++) 
{ 
dataGridView1.SelectedCells[i].Value = true; 
} 
+0

謝謝你傑里米,這完美的作品。 – saas 2012-03-28 06:03:44

相關問題