Alex
Alex

Reputation: 509

Unable to make DataGridView Columns readonly

I am making an application where the user can enter and exit and "edit" state on different items. When entering the edit state, I want to enable certain columns on a DataGridView and when they exit, disable them. The code below is run when the Boolean EditMode changes.

'Change ReadOnly to Not EditMode
'dgv.ReadOnly = Not EditMode                           'Works
dgv.Columns("colCode").ReadOnly = Not EditMode         'Does not work
dgv.Columns("colText").ReadOnly = Not EditMode         'Does not work
dgv.Columns("colTarget").ReadOnly = Not EditMode       'Does not work
dgv.Columns("colCheck").ReadOnly = Not EditMode        'Does not work

When changing the entire DataGridView ReadOnly property, the grid becomes editable/not editable like I would expect it too, but I only want to enable 4/6 columns. The column names are correct, and the logic is the same, but enabling the columns individually is not changing the ReadOnly property and I am not able to edit the columns. Stepping through the debugger, when entering edit mode I can see dgv.Columns("colCode").ReadOnly = Not EditMode evaluate to dgv.Columns("colCode").ReadOnly = False but stepping past, the ReadOnly property remains true...

Upvotes: 2

Views: 7902

Answers (2)

Niranjan Singh
Niranjan Singh

Reputation: 18290

Refer this - How to make a specific Column Uneditable In datagridview?

You will find different details about setting the column read only.

You can make a column read only before binding the data:

this.dgrid.Columns("colName").ReadOnly = true

If you need to do for individual cells within the column, then you will have to loop and set them like this:

this.dgridvwMain.Rows(index).Cells("colName").ReadOnly = true

Then another way is to handle the CellBeginEdit event and set e.Cancel = True when you need disable the cell.

Private Sub DataGridView_CellBeginEdit(sender As System.Object, e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles DataGridViewMsg.CellBeginEdit
    If DataGridViewMsg.Rows(e.RowIndex).Cells("disable").Value = "Y" Then
        e.Cancel = True
    End If
End Sub

References:
How to: Make Columns Read-Only in the Windows Forms DataGridView Control DataGridViewColumn.ReadOnly Property

You can set ReadOnly Property at three levels. You can make entire dataGridView or entire column or entire row as ReadOnly .

dataGridView1.ReadOnly = true;

dataGridView1.Rows[index].ReadOnly = true;

dataGridView1.Columns[index].ReadOnly = true;

Note: DataGridView.ReadOnly property override the column or cell's ReadOnly property. First set the it to false and then change for specific column or cell.

Upvotes: 1

FloatingKiwi
FloatingKiwi

Reputation: 4506

If dgv.ReadOnly = true then the columns are all forced to be ReadOnly = True. So set dgv.ReadOnly = False and set the ReadOnly property only on the columns to true.

Upvotes: 6

Related Questions