How can we disable a cell of datagrid in vb.net and how to show date in datagrid cell in vb.net

Dani AI

Generated

Good start, , and was right to ask for clarification: "disable" usually means prevent the user from editing a cell, not removing selection or hiding it. The approach in the thread works, but setting ReadOnly inside a CellClick handler means the cell remains editable until clicked. It’s more robust to set the read-only state when you create or bind the grid, or to cancel edits when editing begins.

To make a column or a specific cell non-editable (done once, e.g., in Form.Load):

' Make an entire column read-only
DataGridView1.Columns("MyColumn").ReadOnly = True

' Or make a specific cell read-only after you know its row index
DataGridView1.Rows(rowIndex).Cells("MyColumn").ReadOnly = True

To block editing conditionally at runtime, cancel the edit in CellBeginEdit:

Private Sub DataGridView1_CellBeginEdit(sender As Object, e As DataGridViewCellCancelEventArgs) Handles DataGridView1.CellBeginEdit
    If e.RowIndex >= 0 AndAlso e.ColumnIndex = 0 Then
        e.Cancel = True  ' prevents the user from entering edit mode for that cell
    End If
End Sub

For showing dates reliably: ensure the column’s ValueType is DateTime and apply a display format; for new rows set a default value in DefaultValuesNeeded:

DataGridView1.Columns("DateCol").ValueType = GetType(DateTime)
DataGridView1.Columns("DateCol").DefaultCellStyle.Format = "MM/dd/yyyy"

Private Sub DataGridView1_DefaultValuesNeeded(sender As Object, e As DataGridViewRowEventArgs) Handles DataGridView1.DefaultValuesNeeded
    e.Row.Cells("DateCol").Value = DateTime.Today
End Sub

Visual tip: make read-only cells look disabled by setting BackColor/ForeColor and matching SelectionBackColor. If the grid is data-bound, ensure the underlying data column is a DateTime type; otherwise formatting won’t behave as expected. Avoid forcing values on CellClick for defaults — that can overwrite user actions; prefer DefaultValuesNeeded or set the value when you add the row programmatically.

Recommended Answers

All 3 Replies

What exactly you mean by disable a cell of datagrid ? Are you trying to make it read only ?

Yes, the user should not be able to edit the value of the cell and also i want to show date in one cell.

Here is the solution i have resolve it

Private Sub dataGridView1_CellClick(ByVal sender As Object, _
    ByVal e As DataGridViewCellEventArgs) _
    Handles DataGridView1.CellClick

        DataGridView1.CurrentRow.Cells(0).ReadOnly = True
        DataGridView1.CurrentRow.Cells(7).Value = Now
    End Sub
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.