簡體   English   中英

如何在DataGridview中檢查是否已選中的CheckBox

[英]How to check a CheckBox in DataGridview that whether it is checked or not

我在Windows窗體的DataGridView中有13個CheckBox,並且我想在選中第一個CheckBox時檢查所有CheckBox,並在取消選中第一個復選框時取消選中所有Checkbox,所以我該怎么做。 我的代碼可用於檢查所有復選框,但在取消選中時會失敗。 我正在使用CellContentClick事件。 這是我的代碼

if (e.ColumnIndex == 1)
            {
                for (int k = 2; k <= 13; k++)
                {
                    DataGridViewCell cell = dataGridView1.Rows[e.RowIndex].Cells[k];
                    DataGridViewCheckBoxCell checkCell = cell as DataGridViewCheckBoxCell;
                    checkCell.Value = true;
                }
            }

嘗試這個:

if (e.ColumnIndex == 1)
{
    DataGridViewCheckBoxCell firstCell =
            dataGridView1.Rows[e.RowIndex].Cells[1] as DataGridViewCheckBoxCell;
    if(firstCell == null)
    {
        return;
    }

    for (int k = 2; k <= 13; k++)
    {
        DataGridViewCell cell = dataGridView1.Rows[e.RowIndex].Cells[k];
        DataGridViewCheckBoxCell checkCell = cell as DataGridViewCheckBoxCell;
        checkCell.Value = firstCell.Value;
    }
}

您使用for循環僅分配true值,還需要將false值分配給復選框,請取消選中所有復選框。

if (e.ColumnIndex == 1)
            {
                for (int k = 2; k <= 13; k++)
                {
                    DataGridViewCell cell = dataGridView1.Rows[e.RowIndex].Cells[k];
                    DataGridViewCheckBoxCell checkCell = cell as DataGridViewCheckBoxCell;
                    checkCell.Value = dataGridView1.Rows[1].Cells[1].Value;
                }
            }

暫無
暫無

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

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