Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow editing of a datagridview programmatically?

I have a datagridview connected to a database. I have a checkbox for enabling the data to be edited in datagridview. If the checkbox is checked then only 1 column of datagridview can be edited, and after editing click on save button to reflect it in database and when checkbox is unchecked editing is disabled.

I've 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 misses the concept of selecting the columns to be edited.

like image 999
HMcompfreak Avatar asked Mar 02 '12 13:03

HMcompfreak


2 Answers

    for (int i = 0; i <= dataGridView1.ColumnCount - 1; i++)
    {
        dataGridView1.Columns[i].ReadOnly = true; 
    }
like image 116
ahmed mohamady Avatar answered Oct 11 '22 18:10

ahmed mohamady


The help provided in this section can only work if your datagridview's own readonly property is set to false. if it isn't the read only property of each column will persist. When you use the smart tag to choose and enable "make grid editable" then the readonly property is set to false. also what's nice in the new generation grid is that you don't have to find the column like in

foreach (var col in grid1.columns)

you can just use the name of the column as chosen or as default "column1.ReadOnly = false". the enumerator has it's own advantages of course.

like image 23
Stanley Gillmer Avatar answered Oct 11 '22 16:10

Stanley Gillmer