Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data formatting in GridView with AutoGenerateColumns true

I've got a GridView in ASP.NET 2.0 with AutoGenerateColumns set to true. It'll be bound at runtime to a DataSet with one of many possible schemas, and I'd rather not set up grids and columns for each possible schema.

Some of the columns in the grid will sometimes be floating point values. It seems the default number formatting turns 0.345 into 0.345000. Is there a way to change the default number format so it trims to a set number of decimals?

like image 622
Tom Hamming Avatar asked Oct 09 '22 05:10

Tom Hamming


1 Answers

You could use strings in your schema instead of floating point for display purposes, and perform the formatting manually, something like this:

EDIT: Without LINQ, you can do the same thing by modifying rows in the schema:

// load source data
DataSet myData = GetDataSet();

// create column for formatted data.
myData.Tables["MyTable"].Columns.Add("AmountFormatted", typeof(string));

// apply formatting
foreach (DataRow dr in myData.Tables["MyTable"].Rows)
    dr["AmountFormatted"] = string.Format("{0:0.###}", dr["Amount"]);

// remove source column and replace with formatted column
myData.Tables["MyTable"].Columns.Remove("Amount");
myData.Tables["MyTable"].Columns["AmountFormatted"].ColumnName = "Amount";

C#, LINQ-Based solution:

var theData = GetDataSchema1();
var dataSource = theData.Tables["MyTable"].Select().Select(dr =>
    new { /* select only columns you want displayed, and apply formatting */
        MyColumn1 = dr["MyColumn1"],
        MyColumn2 = dr["MyColumn2"],
        MyColumn3 = String.format("#.###", dr["MyColumn3"]),
        MyColumn4 = dr["MyColumn4"],
        MyColumn5 = dr["MyColumn5"]
    }
);
MyGridView1.DataSource = dataSource;
MyGridView1.DataBind()
like image 171
mellamokb Avatar answered Oct 13 '22 10:10

mellamokb