Cách chọn tất cả các hộp kiểm trong datagridview

lập trình


xin chào, tôi đã viết mã bên dưới để chọn tất cả các hộp kiểm nhưng tôi không thể làm như vậy. Vui lòng trợ giúp

Những gì tôi đã thử:

CheckBox HeaderCheckBox=null;
    bool IsHeaderCheckBoxClicked=false;
    private void AddHeaderCheckBox()
    {
        HeaderCheckBox= new CheckBox();
        HeaderCheckBox.Size=new Size(15,15);
        //add check ti DGV
        this.dataGridView1.Controls.Add(HeaderCheckBox);
    }
    private void HeaderCheckBoxClick(CheckBox HCheckBox)
    {
        IsHeaderCheckBoxClicked =true;
        foreach(DataGridView Row in dataGridView1.Rows)
            (DataGridViewCheckBoxCell)Row.CellStateChanged["chk"].value=HCheckBox.Checked;
    }

public void MainFormLoad(object sender, EventArgs e)
		{	

AddHeaderCheckBox();
		}

Giải pháp 1

foreach (DataGridViewRow row in dataGridView1.Rows)
{
       DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell) row.Cells[0];
       chk.Value = !(chk.Value == null ? false : (bool) chk.Value); //because chk.Value is initialy null
}

Giải pháp 2

Xin chào tôi đã viết mã này thay đổi tất cả của các hộp đã chọn sang trạng thái ngược lại của hộp kiểm đầu tiên, trong trường hợp của tôi, hộp kiểm nằm ở cột thứ 3 của chế độ xem dữ liệu.

C#
private void button1_Click(object sender, EventArgs e){
bool state= (bool)tblDocumentos.Rows[0].Cells[2].Value; //stores the state of the first row checkbox
    
foreach (DataGridViewRow row in mydatagridview.Rows)
    {
        row.Cells[2].Value = !state; //Sets the state of each checkbox to the opposite state of the first checkbox
    }
}

Hy vọng nó giúp

コメント

タイトルとURLをコピーしました