Quick check to see if Columnname exists in a datagridview

  • Thread starter Thread starter RSH
  • Start date Start date
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
 
Silly me!

In case anyone else was wondering...

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

{

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

}
 
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
 
Please use "Contains". :o)

Regards,
Lars-Inge Tønnessen
Siemens Medical - Norway
 
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.
 
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
 
Back
Top