[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 734
  • Last Modified:

How to make DataGridView Columns read only

I have a WinForm that has a DataGridView.  When the form opens I want to enable/diable certain fields based on who is logged in, so in the form's load event I am trying to disable editing of certain fields.  The below two statements give me the following errror:  NullReferenceException occurred.  Object reference not set to an instance of an object.  Is there any difference for a DataGrid Please advise what I need to do to resolve.  thanks.

            Me.DataGridView1.Columns.Item("FieldName").Visible = True
            Me.DataGridView1.Columns.Item("FieldName").ReadOnly = True
0
KentDBerry
Asked:
KentDBerry
2 Solutions
 
jacieslaCommented:
Datagridview1.Columns(3).ReadOnly = True

This will make the 3rd column read only. Let me know if this works for you. If not please give me the specific error you receive.
0
 
vb_jonasCommented:
DataGridView1.Columns("FieldName").ReadOnly
0
 
Jorge PaulinoIT Pro/DeveloperCommented:
DataGridView1.Columns("ColumnName").ReadOnly = True
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
KentDBerryAuthor Commented:
DataGridView1.Columns("FieldName").ReadOnly  gives the same error as does
DataGridView1.Columns("ColumnName").ReadOnly = True

jaciesla's below code works but I need to reference the column by its actual text name like "FieldName".  jaciesla, how would you do that?
Datagridview1.Columns(3).ReadOnly = True works
0
 
Jorge PaulinoIT Pro/DeveloperCommented:
DataGridView1.Columns("ColumnName").ReadOnly = True works like Datagridview1.Columns(3).ReadOnly = True

The problem is that you must know the column name that is could by different from the column text. You can do this to get the right name:

MessageBox.Show(Datagridview1.Columns(3).Name)
0
 
Jorge PaulinoIT Pro/DeveloperCommented:
You an use the index (as integer) or the name (as string)
0
 
jacieslaCommented:
The code provided by others ie. DataGridView1.Columns("ColumnName").ReadOnly = True
should work the same as mine. I just prefer to reference my columns numerically. Is it possible that the name of the column is not spelled correctly? That is the only thing I can think of that would cause problems.
Thanks,
James
0

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now