Search code examples
c#datatabledatacolumn

c# Datacolumn in datatable set decimal place


I have a DataColumn in a DataTable created like this:

        DataTable oDt = new DataTable("mytable");
        oDt .Columns.Add("price", Type.GetType("System.Decimal"));

When I enter a value

        DataRow oRow = oDt .NewRow();
        oRow["price"] = 1;
        oDt.Rows.Add(oRow);

I only see 1 and not 1.00 as I would like, being a decimal column. Where am I wrong? How can I automatically see two decimal places? To see the data I use a DataGridView


Solution

  • You can do as below:

    int priceIndex = 1; // Index of the price column
    dataGridView.Columns[priceIndex].DefaultCellStyle.Format = "0.00##"
    

    If you don't have the price column's index then you can do it directly using the column name:

    dataGridView.Columns["price"].DefaultCellStyle.Format = "0.00##"