rul3z
rul3z

Reputation: 183

Prevent Checkbox un/check in DataGridView from being toggled automatically

I have a datagridview with a column checkbox

enter image description here

What I want is if a checkbox click (i use CellContentClick Event) I want show a messageBox that if user press ok .. then checkbox is checked and new query start. Else press Annul or Close Messagebox -> unchecked checkbox .

But I have a problem to implement it:

private void dgvApprovazione_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
        try
        {
            if (dgvApprovazione.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewCheckBoxCell)
            {
                CheckBox checkboxTmp = sender as CheckBox;

                checkboxTmp.AutoCheck = false;
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
}

EDIT: I haven't access to design windows. Checkbox is a dynamic column that is result of read DB.

Column in the database is a true/false type .. In datagridview I have a checkbox with check or uncheck.

I want capture and prevent autocheck in 'code-time'

Upvotes: 1

Views: 2313

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125197

You can make the column read only at start up or when you add the column using ReadOnly property of the column, then handle CelllContentClick and show the message box and set the value of cell based on message box result:

private void Form1_Load(object sender, EventArgs e)
{
    //Load data
    //Add columns

    //I suppose your desired coulmn is at index 0
    this.dataGridView1.Columns[0].ReadOnly = true;
}

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    //I suppose your desired coulmn is at index 0
    if (e.ColumnIndex == 0 && e.RowIndex >= 0)
    {
        var result = MessageBox.Show("Check Item?", "", MessageBoxButtons.YesNoCancel);
        if (result == System.Windows.Forms.DialogResult.Yes)
        {
            ((DataGridView)sender)[e.ColumnIndex, e.RowIndex].Value = true;
        }
        else
        {
            ((DataGridView)sender)[e.ColumnIndex, e.RowIndex].Value = false;
        }
    }
} 

There is not a real CheckBox in the cell and the sender of event is DataGridView.

Upvotes: 3

Related Questions