Quick check to see if Columnname exists in a datagridview

R

RSH

Hi,

I have a situation where I have a dynamically loaded DataGridView and I need
to see if a particular column exists in the DataGridView before I enable it
for editing. Is there an easy way to see if the column exists?

Thanks!
Ron
 
R

RSH

Silly me!

In case anyone else was wondering...

if (dataGridView1.Columns["Modified"] != null)

{

dataGridView1.Columns["Modified"].ReadOnly = true;

}
 
L

Lars-Inge Tønnessen \(VJ# MVP\)

Please use the "Columns.Contains("column name")" method.
Example:

Lets say we have a DataGrid called "dataGridView1".

this.dataGridView1.Columns.Add("One", "One");

if (this.dataGridView1.Columns.Contains("One"))
System.Windows.Forms.MessageBox.Show("Yes");

this.dataGridView1.Columns.Add("Two", "Two");
this.dataGridView1.Columns.Add("Three", "Three");


Regards,
Lars-Inge Tønnessen
Siemens Medical - Norway
 
L

Lars-Inge Tønnessen \(VJ# MVP\)

Please use "Contains". :blush:)

Regards,
Lars-Inge Tønnessen
Siemens Medical - Norway
 
G

Guest

1. Its a more reliable method of determining if a column exists. By your
method what if you port your code to .Net 2.x and in the new version it does
not return null but instead it returns an empty column?

2. Its just better coding practice. It begs the question, why did Microsoft
bother giving you a Contains method? Think about it.

3. It also explicitly states your intentions, which is probably the most
important factor of all.
 
L

Lars-Inge Tønnessen \(VJ# MVP\)

The Microsoft developers always use this method when they are writing code.
I guess it has something to do with forward compatibility and stability.

Regards,
Lars-Inge Tønnessen
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top