【问题标题】:a check if a dataGridView checkBox is checked is failing检查是否选中了 dataGridView 复选框失败
【发布时间】:2018-10-31 17:45:04
【问题描述】:

有一个像here 这样的问题的答案,但我的问题是为什么这样做代码是不起作用所以请不要将其标记为该问题的“重复”

所以我有一个 dataGridView 和一个复选框。所以我希望在选中和取消选中此框时发生一些事情,所以我这样做:

private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
     Trace.WriteLine("Cell Content Click Col: " + e.ColumnIndex + " Row: " + e.RowIndex);

     if(e.ColumnIndex==0) //0 is the column of the checkbox
     {
       Trace.WriteLine("Value:"+  dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
     }
}

如您所见,我正在应用另一个问题的答案。但是结果是,无论我选中还是取消选中该框,该值都是 always false。

我打算用 CellValidating 试试这个,看看我是否能得到更好的结果,但是检查一个框是否被选中或取消选中 dataGridView 的最佳方法是什么?

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:

    取自 this answer 您在问题中发布的同一链接:

    编辑DataGridView中的值后,您应该首先提交更改,以便正确更新表中的内部值:

    private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
    {
        if (dataGridView1.IsCurrentCellDirty)
        {
            dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }
    }
    

    只有这样,才能正确查询复选框的状态:

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        DataGridView dgv = (DataGridView)sender;
    
        if (dgv.Rows.Count >= e.RowIndex + 1)
        {
            bool isChecked = (bool)dgv.Rows[e.RowIndex].Cells["CheckColumn"].Value;
            MessageBox.Show(string.Format("Row {0} is {1}", e.RowIndex, isChecked));
        }
    }
    

    【讨论】:

      【解决方案2】:
      private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
      {
          Trace.WriteLine("Cell Content Click Col: " + e.ColumnIndex + " Row: " + e.RowIndex);
      
          if (e.ColumnIndex == 0)
          {
              DataGridViewCheckBoxCell cell = dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;
              if (cell != null)
              {
                  Trace.WriteLine("Value:" + cell.EditingCellFormattedValue);
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2013-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-28
        相关资源
        最近更新 更多