Refer to DataGridView column by string name

Welcome to Wisej Support.
Questions, suggestions and plain old bugs - are all welcome here!
0
0

Hi,

I can’t seem to make the following work.  Add a DataGridView control with 2 columns, contactID and firstName.

Refer to the firstName column:  var col = this.datagridView1.Columns[“firstName”];  gives me a null reference.

Refer to the column by the index: var col = this.datagridView1.Columns[1];  works just fine.

Hopefully it’s something obvious that i’m missing here.  Any help appreciated!

  • You must to post comments
0
0

Hi,

You have to set the column names explicitly. I suspect that you have AutoGenerateColumns = true and you just set the datasource. This procedure does not give column names. And this is why you get the null exception. But of course this may be a wrong assumption.

Alex

 

  • You must to post comments
0
0

Hi Andrew,

I tried to reproduce but failed. (see simple sample attached).

Are you sure that the name is set to the columns ? Sometimes the designer plays tricks on you.

Any chance to provide us with a test case ?

Thanks in advance.

Best regards
Frank

Attachment
  • Andrew Hills
    Hi Frank/Alex, I’ve figured out what the problem was. That example you sent through Frank contained the reference Wisej.Web.Design. When I create a Wisej solution, it doesn’t include that reference by default, so what ends up happening is when a Datagridview control is added to a form, then add a couple of columns in the designer, there’s a bunch of properties that do not show up, one of which is the ‘name’ property which falls under the ‘Design’ category. As soon as I add Wisej.Web.Design to my references then open up the DGV designer again, the ‘Design’ category shows up and I can edit the name of the column. Because that name property was not previously visible in the designer, the default name for the columns were Column0 for contactID and Column1 for firstName which is why I got a null reference, i.e. I could only set the ‘DataPropertyName’ not the actual column name. What is a bit odd though is using that example you sent through Frank, if I remove the Wisej.Web.Design reference, rebuild, and check the DGV designer, those previously missing properties are still there. If I delete the DGV and add a new one plus add some columns, that’s when the properties go missing again. It’s not a big deal, just something that I will need to keep an eye on when creating new applications. Thanks for your help.
  • You must to post comments
Showing 2 results
Your Answer
Post as a guest by filling out the fields below or if you already have an account.
Name*
E-mail*
Attachment
File Name Size
There are currently no files uploaded.
Maximum number of files 1, maximum file size 3.9MB.
Supported file formats: zip pdf gif jpg bmp png cs vb theme json