2016-10-02 31 views
1

我有一个复选框[All]和如下一个DataGridView:如何处理datagridview中的组合框事件?

enter image description here

我想:

  • 内部datagridview的,如果所有的复选框被选中,复选框[All]是检查,否则如果所有复选框未选中,复选框[All]未选中
  • 内部datagridview,有一个未选中复选框,复选框[All]没有被选中

我尝试过,但我没有能够做到这一点:

private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e) 
{ 
    bool isAllCheck = false; 

    if (e.ColumnIndex == 0) 
    { 
     foreach (DataGridViewRow row in dataGridView.Rows) 
     { 
      DataGridViewCheckBoxCell chk = row.Cells[0] as DataGridViewCheckBoxCell; 

      isAllCheck = Convert.ToBoolean(chk.Value); 
      if (!isAllCheck) 
      { 
       break; 
      } 
     } 

     if (chkAllItem.Checked && !isAllCheck) 
     { 
      chkAllItem.Checked = false; 
     } 

     if (!chkAllItem.Checked && isAllCheck) 
     { 
      chkAllItem.Checked = true; 
     } 
    } 
} 

private void dataGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e) 
{ 
    if (this.dataGridView.IsCurrentCellDirty) 
    { 
     this.dataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit); 
    } 
} 

这些任何提示将是很大的帮助。提前致谢。

+0

_ “不能够做到这一点” _ ....什么没有奏效? –

+0

我很抱歉没有清楚解释。 “不能这样做”....意思是:在datagridview里面,如果我取消选择一个复选框,所有的复选框都没有选中。不过,得益于TaW先生的指导,我做得很好。 – MinhKiyo

回答

1

设置TrueValue,FalseValueIndeterminateValue是一个好的开始。

我发现我还需要做一些更多的工作;除了你CurrentCellDirtyStateChanged事件我也编码这些:

这将所有CheckBoxCells

private void cbx_all_CheckedChanged(object sender, EventArgs e) 
{ 
    if (cbx_all.Tag == null) for (int i = 0; i < dataGridView.RowCount; i++) 
    { 
     dataGridView.Tag = "busy"; 
     dataGridView[yourCheckBoxcolumnIndex, i].Value = cbx_all.Checked; 
     dataGridView.Tag = null; 
    } 
} 

我编写了CellValueChanged,而不是CellContentClick事件:

private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e) 
{ 
    if (e.ColumnIndex == yourCheckBoxcolumnIndex && dataGridView.Tag == null) 
    { 
     cbx_all.Tag = "busy"; 
     cbx_all.Checked = testChecks(e.ColumnIndex); 
     cbx_all.Tag = null; 
    } 
} 

我用的Tag财产DGVCheckBox作为标志,我忙于改变价值鳕鱼即避免无限循环的一些其他方法也同样适用。

这是测试功能:

bool testChecks(int index) 
{ 
    for (int r = 0; r < dataGridView.RowCount; r++) 
     if (!(bool)dataGridView[index, r].Value) return false; 
    return true; 
} 
+0

是的,确切地说。非常感谢你! – MinhKiyo

1

DataGridViewCheckBoxCell具有性能TrueValueFalseValueIndeterminateValue其默认值是null。这些值由属性Value给出,取决于复选框的状态。由于Convert.ToBooleannull转换为false,如果属性未初始化,转换的结果始终为false

这些可以在单元本身或其拥有的列上初始化。

您需要将拥有的列TrueValue初始化为trueFalseValuefalse

+0

谢谢你的回复! – MinhKiyo

相关问题