2012-07-23 47 views
0

所有選定的動態調用我已經添加了具有包括DataGridCheckBoxColumn動態數據網格,並觸發選項卡上的動態複選框選擇所有的DataGrid的複選框動態標籤。如何使當複選框選擇每個TabPage的每DataGrid中

我想實現沿着這些線路的東西。

private void cbSelectAll_CheckedChanged(object sender, EventArgs e) 
{ 

    if (cbSelectAll.Checked) 
    { 
     foreach (DataGridViewRow row in relatedPatientsDG.Rows) 
     { 
      row.Cells[0].Value = true; 
     } 
    } 
    else 
    { 
     foreach (DataGridViewRow row in relatedPatientsDG.Rows) 
     { 
      row.Cells[0].Value = false; 
     } 
    } 
} 

但這種方法是動態的作爲需要驗證的選項卡/數據網格DataGridCheckBoxColumn被選中是因爲我的標籤上動態創建每件事情做好。

舉個例子,如果我有一個名爲relatedDG的數據網格有DataGridColumnCheckBox那麼事件的方法來觸發選擇所有,並取消所有會是什麼樣。我需要做一個類似的更改,但對於動態datagridcheckbox,因此沒有硬編碼。

private void cbSelectAllSameVisits_CheckedChanged(object sender, EventArgs e) 
{ 
    if (cbSelectAllSameVisits.Checked) 
    { 
     foreach (DataGridViewRow row in relatedDG.Rows) 
     { 
      row.Cells[0].Value = true; 
     } 

    } 
    else 
    { 
     foreach (DataGridViewRow row in relatedDG.Rows) 
     { 
      row.Cells[0].Value = false; 
     } 
    } 
} 

回答

0

您可以利用這樣一個事實:網格和複選框的每一對都在同一個頁面上 - 它們都是同一個容器控件的子對象。

這可以讓你有你連接上創建CheckedChanged事件的所有複選框的一個方法:

private void checkBox_CheckedChanged(object sender, EventArgs e) 
{ 
    CheckBox cb = sender as CheckBox; 
    DataGridView dg = cb.Parent.Controls.Cast<Control>() 
         .Where(c => c.GetType() == typeof(DataGridView)) 
         .FirstOrDefault() as DataGridView; 

    if (dg != null) 
    {    
     if (cb.Checked) 
     { 
      foreach (DataGridViewRow row in dg.Rows) 
      { 
       row.Cells[0].Value = true; 
      } 
     } 
     else 
     { 
      foreach (DataGridViewRow row in dg.Rows) 
      { 
       row.Cells[0].Value = false; 
      } 
     }   
    }    
} 

該代碼使用事件處理程序的sender參數來識別被點擊的複選框然後搜索屬於第一個DataGridView的複選框父級的控件。

相關問題