Home > Mobile >  C# Make other button column cell unclickable when one of the cell is clicked
C# Make other button column cell unclickable when one of the cell is clicked

Time:12-23

I had a GUI that have a datagridview with button column.

Pic

I set the button enabled property to false once I click on the button cell.

Pic2

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {                 
            DataGridView senderGrid = (DataGridView)sender;
            if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0)
            {
                //....
               DataGridViewDisableButtonCell btnClick = (DataGridViewDisableButtonCell)dataGridView4.Rows[e.RowIndex].Cells[e.ColumnIndex];
               btnClick.Enabled = false;
        
               //execude code
        
               btnClick.Enabled = true;
             }                                   
        }

My question is how I make the other cell unclickable also to prevent the code run when one of the button cell is clicked?

CodePudding user response:

You need to get the cells of type DataGridViewDisableButtonCell to get or set their properties. To avoid repeating the same code, create a method to toggle the Enabled property.

private void SetEnabled(bool enabled)
{
    foreach (var cell in senderGrid.Rows.OfType<DataGridViewRow>()
        .SelectMany(x => x.Cells
        .OfType<DataGridViewDisableButtonCell>())) 
        cell.Enabled = enabled;
}

In case you have multiple columns of that type and you want to apply the change on a specific one, then you need to specify the target column:

private void SetEnabled(bool enabled, int columnIndex)
{
    foreach (var cell in senderGrid.Rows.OfType<DataGridViewRow>()
        .SelectMany(c => c.Cells
        .OfType<DataGridViewDisableButtonCell>()
        .Where(col => col.OwningColumn.Index == columnIndex)))
        cell.Enabled = enabled;
}

Using the method in your code:

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

    if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0)
    {
        SetEnabled(false);
        // Or
        // SetEnabled(false, e.ColumnIndex);

        //execude code

        SetEnabled(true);
        // Or
        // SetEnabled(true, e.ColumnIndex);
    }
}
  • Related