Search code examples
vb.netdatagridviewcellsdatagridviewbuttoncolumn

How to hide a DataGridViewButtonCell


I have a DataGridViewButtonCell in my DataGridView and I wanted to set the property Visible to True.

I have tried:

DataGridView1.Rows("number of row i want").Cells("number of cell i want").Visible = True

Unfortunately it says that the property visible is read only.

Here is the code:

Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
        'does not work
        DataGridView1.Rows(e.RowIndex).Cells(6).Visible = True         
End Sub

Does anyone knows how I can achieve this?

Thanks.


Solution

  • There is no actual way to hide a DataGridViewButtonCell. Currently I can only see two options:

    1. Use padding to move the button over as shown here. I will provide similar VB.NET code
    2. Set the Cell to a DataGridViewTextBoxCell and set the ReadOnly property to True

    Use Padding:

    Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
        If DataGridView1.Rows(e.RowIndex).Cells(6).GetType() Is GetType(DataGridViewButtonCell) Then
            Dim columnWidth As Integer = DataGridView1.Columns(e.ColumnIndex).Width
    
            Dim newDataGridViewCellStyle As New DataGridViewCellStyle With {.Padding = New Padding(columnWidth + 1, 0, 0, 0)}
    
            DataGridView1.Rows(e.RowIndex).Cells(6).Style = newDataGridViewCellStyle
        End If
    End Sub
    

    Use DataGridViewTextBoxCell:

    Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
        If DataGridView1.Rows(e.RowIndex).Cells(6).GetType() Is GetType(DataGridViewButtonCell) Then
            Dim newDataGridViewCell As New DataGridViewTextBoxCell
    
            DataGridView1.Rows(e.RowIndex).Cells(6) = newDataGridViewCell
    
            newDataGridViewCell.ReadOnly = True
        End If
    End Sub
    

    Both of these should give you the effect of not showing the button.