SoFunction
Updated on 2025-03-07

C# Operation DataGridView Set Cell Read-Only

1. Modify the ReadOnly property

1. Set the entire DataGridView to read-only:

=true;

At this time, the user's new row and delete row operations are also blocked.

2. Set a cell in DataGridView that cannot be edited, for example: Set a cell in the first column of the second row and the first column cannot be edited:

this.dgv_PropDemo[0, 1].ReadOnly = true;

3. Set the entire column of DataGridVIew that cannot be edited, for example: Set the second column that cannot be edited:

this.dgv_PropDemo.Columns[1].ReadOnly = true;

4. Set the entire line of the DataGridView cannot be edited, for example: Set the third line cannot be edited:

this.dgv_PropDemo.Rows[2].ReadOnly = true;

2. Use EditMode property

EditMode property: Gets or sets a value that indicates how to start editing a cell. The property value is one of the DataGridViewEditMode enumeration values.

Member Name illustrate
EditOnEnter Editing begins when the cell receives focus. This mode is useful when pressing the Tab key to enter values ​​horizontally in a row, or pressing the Enter key to enter values ​​vertically in a column.
EditOnF2 Press F2 to start editing when the cell gets focus. This mode places the selection point at the end of the cell content.
EditOnKeystroke Press any alphanumeric keys to start editing when the cell gets focus.
EditOnKeystrokeOrF2 Press any alphanumeric key or F2 to start editing when the cell gets focus. default value
EditProgrammatically Editing is only started when the BeginEdit method is called.

Note: ExceptEditProgrammaticallyOutside, all DataGridViewEditMode values ​​allow the user to start editing the cell by double-clicking it.

When the EditMode property of DataGridView is set to EditProgrammatically, the user cannot manually edit the content of the cell. However, the program can be used to call the method to make the cell enter the edit mode for editing.

For example:

this.dgv_PropDemo.BeginEdit(true);

3. Set the uneditable state of the cell according to the conditions

When it is too troublesome to set the ReadOnly attribute of the cell one by one, you can cancel the editing of the cell through the CellBeginEdit event.

Example:

 private void dgv_PropDemo_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            DataGridView dgv = sender as DataGridView;
            //Cancel editing when the column name of the current cell is equal to Sex and the value of the current cell is equal to "male".            if ([].Name == "Sex" && dgv[, ].().Trim() == "male")
            {
                //Cancel Edit                 = true;
            }
        }

This is all about this article about C# operation DataGridView setting cell read-only. I hope it will be helpful to everyone's learning and I hope everyone will support me more.