Winforms – Datagridview, disable button/row

buttondatagridviewdelete-rowwinforms

I have a datagridview on a form with some data. The 1st column contains button for deleting the row. How can we disable this button or the entire row based on some condition, so the row cannot be deleted?

Best Answer

Would you consider just turning the button cell into a regular empty text box disabled?

Dim cell As DataGridViewButtonCell = dgv.row(x).cell(y)
cell = New DataGridViewTextBoxCell()
cell.value = String.Empty
cell.ReadOnly = True

It loses its bordered "Button" appearance and blends in with the remainder of the cells (assuming you are using primarily the default DataGridViewTextBoxCells).

Here's the equivalent in C#, plus it grays out the field to make it look read-only:

var cell = dgv[column, row] = new DataGridViewTextBoxCell();
cell.Value = ""; // ignored if this column is databound
cell.ReadOnly = true;
cell.Style.BackColor = Color.FromKnownColor(KnownColor.Control);