Search code examples
vb.netvisual-studio-2019

vb.net Datagridview CheckBox column


I have a Datagridview with CheckBox column, I want to unable to check the checkbox of if the stock is 0 and Messagbox that the stock is 0

enter image description here

Here is my code:

 Private Sub dgv_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles dgv.CellEndEdit
        Dim selected As String = dgv.Rows(e.RowIndex).Cells("checkbox").Value

        If dgv.Rows(e.RowIndex).Cells("checkbox").Value = True Then
            If dgv.Rows(e.RowIndex).Cells(9).Value <= 0 Then   'cell9 item stock
                dgv.Rows(e.RowIndex).Cells("checkbox").Value = False
                MsgBox("Invalid Stocks is 0")
            End If
        Else
        End If
    End Sub
End Class

Solution

  • You can set the cell to ReadOnly first then change its value.

    Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgv.CellContentClick
        If e.ColumnIndex = 0 AndAlso dgv.Rows(e.RowIndex).Cells(6).Value = 0 Then
            dgv.Rows(e.RowIndex).Cells(e.ColumnIndex).ReadOnly = True
            dgv.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = False
            MessageBox.Show("Invalid Stocks is 0")
        Else
            dgv.Rows(e.RowIndex).Cells(e.ColumnIndex).ReadOnly = False
        End If
    End Sub