2012-07-23 48 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的复选框父级的控件。

相关问题