Formatting a column in a datagridview to currency

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Cdude

    #1

    Formatting a column in a datagridview to currency

    I am using this code at the moment to format the column

    this.itemsDataG rid.Columns["Amount"].DefaultCellSty le.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

    #2
    Re: Formatting a column in a datagridview to currency

    On May 9, 8:53 am, Cdude <camelj...@yaho o.comwrote:
    I am using this code at the moment to format the column
    >
    this.itemsDataG rid.Columns["Amount"].DefaultCellSty le.Format = "c";
    >
    but i get the error "Object reference not set to an instance of an
    object. " is this code incorrect ?
    Any suggestions please
    Got it thanks

    Comment

    • Marc Gravell

      #3
      Re: Formatting a column in a datagridview to currency

      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

      Comment

      • Marc Gravell

        #4
        Re: Formatting a column in a datagridview to currency

        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.ColumnAdde d += (s, a) =>
        {
        if (a.Column.DataP ropertyName == "Amount")
        {
        a.Column.Defaul tCellStyle.Form at = "c";
        }
        };using System;
        using System.Componen tModel;
        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.ColumnAdde d += (s, a) =>
        {
        if (a.Column.DataP ropertyName == "Amount")
        {
        a.Column.Defaul tCellStyle.Form at = "c";
        }
        };

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

        }
        }

        Comment

        Working...