简体   繁体   中英

How to check more than one checkbox individually in DataGridView C#

I would like how to achieve this, I tried many of the solutions i found on here on SO but none of them worked

在此处输入图片说明

I want to be able to check for example the first and the second option but when i check one of them the others two are unchecked, how can avoid this?

I would like to know what events or properties i need to change to be able to select multiple checkboxes individually no using a master checkbox to select all of them, I hope you can help me thanks.

I tried this code in the CellClick event of the datagridview

var isChecked = (bool)DGVProductos.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

if (isChecked)
{
    foreach (DataGridViewRow row in DGVProductos.Rows)
    {
        if (row.Index != e.RowIndex)
        {
            row.Cells["CheckProducto"].Value = !isChecked;
        }
    }
}

I'm not sure what your foreach loop is trying to accomplish, but it is unchecking all of the other boxes that are not the row that was checked. If you want the boxes checked individually and to stay checked, remove the foreach loop.

Its not clear what you try to achieve there, the code you wrote does exactly the opposite from what you are describing, just remove that code and you should be able to check individual cells.

Though if you are trying to use that column as a Selection-Indicator, thus the column is not bound to any property, note, that this is not possible, since the column is not bound to the objects checking 1 row-cell will automatically check all rows and vice versa.

Side Note: Whatever you want to achieve, code that needs to run when a user check/uncheck a checkbox, should be invoked on CellContentClick event rather then CellClick event.

I found a solution to what I was trying to achieve I will let the code on here for reference to anyone else facing this same issue

private void DGVProductos_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 0)
    {
        if ((bool)DGVProductos.SelectedRows[e.ColumnIndex].Cells["CheckProducto"].Value == false)
        {
            DGVProductos.SelectedRows[e.ColumnIndex].Cells["CheckProducto"].Value = true;
        }
        else
        {
            DGVProductos.SelectedRows[e.ColumnIndex].Cells["CheckProducto"].Value = false;
        }
    }    
}

This way i'm able to check more than one checkbox indivually like the question says, not sure if is the best way but this worked for me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM