简体   繁体   中英

Get DataGridView checkbox value after changed

i have DataGridView with several columns, every Row represent my object with several properties like name, id etc. after change my Name column Checkbox i want to update my object How can i get my column Checknox state ? This is what i have try:

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

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (dataGridView1.Columns[e.ColumnIndex].Name == "Name")
    {

    }
}

I assume Name is the name of DataGridViewCheckBoxColumn

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (dataGridView1.Columns[e.ColumnIndex].Name == "Name")
    {
        var isChecked = dataGridView1[e.ColumnIndex, e.RowIndex].Value as bool? ?? false;
        //rest of logic
    }
}

this is the simplest and safest way.

To iterate through all cells in row use this code:

DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
foreach (DataGridViewCell cell in row.Cells)
{
   object value = cell.Value;
}

Maybe you can use the FindControl() to get the state of checkbox:

CheckBox cbName = (CheckBox)dataGridView1.Columns[e.ColumnIndex].FindControl("cbName");
checkState = cbName.CheckState.toString();

or

isChecked = cbName.Checked;

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