簡體   English   中英

檢查是否檢查了 dataGridView checkBox 失敗

[英]a check if a dataGridView checkBox is checked is failing

有這樣一個問題的答案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);
     }
}

如您所見,我正在應用另一個問題的答案。 但是結果是,無論我選中還是取消選中該框,該值始終為false。

我打算用 CellValidating 來試試這個,看看我是否能得到更好的結果,但檢查一個框是否被選中或取消選中 dataGridView 的最佳方法是什么?

取自您在問題中發布的同一鏈接上的答案

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));
    }
}
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);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM