Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Formatting a column in a datagridview to currency

3 views
Skip to first unread message

Cdude

unread,
May 9, 2008, 2:53:47 AM5/9/08
to
I am using this code at the moment to format the column

this.itemsDataGrid.Columns["Amount"].DefaultCellStyle.Format = "c";

but i get the error "Object reference not set to an instance of an
object. " is this code incorrect ?
Any suggestions please

Cdude

unread,
May 9, 2008, 3:07:42 AM5/9/08
to

Got it thanks

Marc Gravell

unread,
May 9, 2008, 3:07:36 AM5/9/08
to
Well, is there a column named "Amount"?

Note that a *column* named "Amount" is different to a column that is
mapped to the *property* named "Amount"...

Marc

Marc Gravell

unread,
May 9, 2008, 3:17:57 AM5/9/08
to
One other thought - if you are letting the grid auto-generate the
columns by attaching a DataSource (rather than by creating explicit
columns), then you need to be aware that the columns won't exist until
the grid needs to display itself. In which case, you can use the
ColumnAdded event as a prompt (below).

Marc

grid.ColumnAdded += (s, a) =>
{
if (a.Column.DataPropertyName == "Amount")
{
a.Column.DefaultCellStyle.Format = "c";
}
};using System;
using System.ComponentModel;
using System.Windows.Forms;

class Foo
{
public decimal Amount { get; set; }
}

class Program
{
[STAThread]
static void Main()
{
BindingList<Foo> data = new BindingList<Foo>();
data.Add(new Foo {Amount = 1.2M});
data.Add(new Foo {Amount = 7.8M});

DataGridView grid = new DataGridView();
grid.Dock = DockStyle.Fill;
grid.DataSource = data;

grid.ColumnAdded += (s, a) =>
{
if (a.Column.DataPropertyName == "Amount")
{
a.Column.DefaultCellStyle.Format = "c";
}
};

Application.EnableVisualStyles();
Application.Run(new Form {Controls = {grid}});

}
}

0 new messages