0
votes

I am using a datagridview in a C# application. And I need that only one specific column be editable, but not the whole column. The last row must be readonly.

I set datagridview readonly property, at design, as false. Then I used the sequence of codes to turn all other columns as readonly:

dataGridView1.Columns["Col1"].ReadOnly = true; dataGridView1.Columns["Col2"].ReadOnly = true; dataGridView1.Columns["Col3"].ReadOnly = true; dataGridView1.Columns["Col4"].ReadOnly = true;

The datagridview has 5 columns. At this point, only the Col5 is editable. But I need the last row to be readonly, so I tried:

dataGridView1.Rows[dataGridView1.Rows.Count - 1].ReadOnly = true;

That didn't work, the whole Col5 is still editable. So I tried:

dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells["Col5"].ReadOnly = true;

That didn't work as well. The whole Col5 was still editable.

How can I solve that?

2

2 Answers

1
votes

Method 1:

You can change the row's (or cell's) read-only state after the data binding is completed:

dataGridView1.DataBindingComplete += dataGridView1_DataBindingComplete;

And,

void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    dataGridView1.Rows[dataGridView1.Rows.Count - 1].ReadOnly = true;
}

Method 2:

You can cancel the edit of any cell if row is the last row:

dataGridView1.CellBeginEdit += dataGridView1_CellBeginEdit;

And;

void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
    e.Cancel = e.RowIndex == dataGridView1.Rows.Count - 1;
}
0
votes

Try to set the datagridview.readonly property in design as true. Last column readonly false. And after that last row as readonly true.