Datagridview, disable button/row
I have a datagridview o开发者_开发知识库n 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?
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);
There's actually a HowTo on MSDN doing exactly this.
Edit: Added some other suggestions.
You can make the button column invisible.
Or if you only want to disable deletion of certain rows you could put in true or false in each DataGridViewRow
s Tag
property and in your button event handler you only delete the ones that are set to false. You could possibly combine this with just changing the foreground and background colours of the cell to make it look disabled, this colouring in could probably be done in the CellFormatting
event handler or something so that you don't have to loop through and colour it in by hand.
This is an old post, but I would like to suggest what I do.
If conditionToDisable Then
Dim cell As New DataGridViewTextBoxCell 'Replace the ButtonCell for a TextCell'
cell.Value = valueForCell 'Set the value again'
grid.Rows(r).Cells(c) = cell 'Override the cell'
End If
I hope this is helpful.
精彩评论