Raj
Raj

Reputation: 165

How to enable and disable particular row in DataGridView by checkbox?

I am trying to enable and disable specific row in DataGridView by checking and unchecking of checkbox inside gridview. (C# Windows application)

I tried using the CellClick event which did not work as expected.

This is the code which i tried

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 0 && dataGridView1.CurrentCell.Selected == true)
    {

        dataGridView1.Columns[3].ReadOnly = false;

    }

}

please tell me how to do this.

Thanks in advance

Upvotes: 4

Views: 25146

Answers (3)

Sudharshan
Sudharshan

Reputation: 348

You can simply use dataGridView "CellContentClick" event. The code goes as bellow.

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    var _dataGrid = (DataGridView)sender;

    //Give your checkbox column Index
    int chkBoxColumnIndex = 1;

    if (e.ColumnIndex == chkBoxColumnIndex && e.RowIndex >= 0)
    {
        bool isChecked = _dataGrid[chkBoxColumnIndex, e.RowIndex].Value == null ? false : (bool)_dataGrid[chkBoxColumnIndex, e.RowIndex].Value;
        for (int i = 0; i < dataGridView1.Columns.Count; i++)
        {
            _dataGrid[i, e.RowIndex].ReadOnly = isChecked;
        }
    }
}

Upvotes: 2

iJay
iJay

Reputation: 4273

I think you missed the CellContentClick event, try this:

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{          
     if (e.ColumnIndex == dataGridView1.Columns["Your Column Name"].Index) //To check that we are in the right column
     {
          dataGridView1.EndEdit();  //Stop editing of cell.
          if ((bool)dataGridView1.Rows[e.RowIndex].Cells["Your Column Name"].Value)
          {
             //dataGridView1.Columns[3].ReadOnly = true;// for entire column 
               int colIndex = e.ColumnIndex;
               int rowIndex = e.RowIndex;
               dataGridView1.Rows[colIndex].Cells[rowIndex].ReadOnly = true;
          }
    }
}

Upvotes: 4

Steven Mays
Steven Mays

Reputation: 365

Well, you're setting the readonly property to false meaning it is NOT read only. Try setting it to true. Also the event that fires this should be the checkbox click event (double click on the checkbox to create the event handler).

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
    dataGridView1.Columns[3].ReadOnly = true;
}

Also, take a look at the frozen property.

dataGridView1.Columns[3].Frozen = true; 

Upvotes: 0

Related Questions