23

I'm using Visual Studio 2012. I want to disable the editing on the DataGridView, it seems to work when I used this code:

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    dataGridView1.ReadOnly = true;
}

But when I get back on the menu form then go back to the form where the DataGridView is, it can now be edit. I only define

dataGridView1.ReadOnly = true;

to this form. And I don't know whats the problem. Can someone help? Thanks.

Here's my code on the button going to the menu

Menu menu = new Menu();
this.Hide();
menu.ShowDialog();

and my button going back to the DataGrid:

FrmList frmlist = new FrmList();
frmlist.Show();
this.Hide();
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jonald Samilo
  • 297
  • 1
  • 2
  • 11

5 Answers5

39

Why don't you try setting the ReadOnly property to True in the Properties window of the DataGridView?

Edit:

Double click on the form and in the design window, select the DataGridView and open the Properties tab. Scroll down through the properties and you will see the ReadOnly option. Change it's value to True.

You were setting the ReadOnly property in the CellContentClick event which will be executed only when user clicks on the grid cells. So, when you create a new object of the form like this,

FrmList frmlist = new FrmList();

it will just create a new instance of the form with the Properties set in the designer. Since the ReadOnly property is set to false by default and the code you wrote to set it to true has not executed, the DataGridView will be editable.

Romy Mathews
  • 797
  • 7
  • 13
3

Ref:

DataGridView read only cells

this.dgridvwMain.Rows[index].Cells["colName"].ReadOnly = true;
Community
  • 1
  • 1
2

add this to your code:

dataGridView1.ReadOnly = true;

or you can change Read Only property in designer mode.

0

Check if the form is reinitialized on navigation. You can set a breakpoint in the constructor. This depends on your navigation service, or how ever it is implemented. In this case you can set the ReadOnly Flag to the last value on initialization or implement it as singleton.

webdude
  • 41
  • 7
0

Make the the entire DataGridView read only. For more information visit MSDN

private void Button8_Click(object sender, System.EventArgs e)
{
    foreach (DataGridViewBand band in dataGridView.Columns)
    {
        band.ReadOnly = true;
    }
}