Brian Smith
Brian Smith

Reputation: 57

Creating new datagridview column formatting

I have a DataGridView on my form. I am trying to format a column to show as currency.

What am I doing wrong here?

this.employeeInfoDataGridView.Columns["Salary"].DefaultCellStyle.Format = "c";

Got this error message:

An unhandled exception of type 'System.NullReferenceException' occurred in...

I am using this on form_load if that makes a difference.

Upvotes: 0

Views: 181

Answers (2)

Wasif Hossain
Wasif Hossain

Reputation: 3950

'System.NullReferenceException' occurs when the particular column named 'Salary' is not yet being created during form_load. In this case, you need to do the following in order to avoid this exception:

if ( this.employeeInfoDataGridView.Columns["Salary"] != null )
{
    this.employeeInfoDataGridView.Columns["Salary"].DefaultCellStyle.Format = "c";
}

And you have to ensure that the specific column is loaded before you set the DefaultCellStyle of that column.

Upvotes: 0

Brian Smith
Brian Smith

Reputation: 57

Figured it out by going into my form > clicking datagridview object > columns property > salary column > default cell style > format > c2.

Still confused as to why I couldn't do it in code the same way. Thanks for the help guys.

Upvotes: 1

Related Questions