How to enable datagridview editing programmatically?

I have a datagridview related to a database. I have a checkbox allowing me to edit data in a datagridview. If the box is checked, then only 1 datagridview column can be edited, and after editing, click the "Save" button to reflect it in the database, and when the box is unchecked, editing is disabled.

I tried something like this:

private void checkBox1_CheckedChanged(object sender, EventArgs e) { if (checkBox1.CheckState == CheckState.Checked) { dataGridView1.CurrentRow.ReadOnly = false; dataGridView1.EditMode = DataGridViewEditMode.EditOnKeystrokeOrF2; } else if (checkBox1.CheckState == CheckState.Unchecked) { dataGridView1.ReadOnly = true; } } 

This code lacks the concept of selecting columns for editing.

+4
source share
4 answers
  for (int i = 0; i <= dataGridView1.ColumnCount - 1; i++) { dataGridView1.Columns[i].ReadOnly = true; } 
+2
source

The help provided in this section can only work if the readonly native property of your datagridview is false. if this is not a read-only property for each column, it will be preserved. When you use the smart tag to select and enable “make the grid editable,” then the readonly property is set to false. also, which is nice in a new generation grid, you do not need to find a column, as in

 foreach (var col in grid1.columns) 

you can simply use the column name as the selected one or the default is "column1.ReadOnly = false". the counter has its advantages, of course.

+2
source

To do what you want, you need to set only the column that you want to disable.

 dataGridView1.Columns[0].ReadOnly = true; dataGridView1.Columns[1].ReadOnly = false; 

But do you want to do this? Lock entire column?

0
source

You can try

 if(dataGridView1.SelectedCells.Count>0) dataGridView1.SelectedCells[0].ReadOnly=false; 

instead

 dataGridView1.CurrentRow.ReadOnly=false; 
0
source

Source: https://habr.com/ru/post/1399395/


All Articles