上周给销售部做了一个报表,老大说里面的数据显示不方便他们使用,要改成财务的那种用“,”隔开的形式。我靠,这个要求也有,150000要表示为150,000。想了好久,最终决定用"string.format("{0:n}",number)"这个来格式化每个数值,当然数据类型也变了。
具体代码如下:

private void FormatNumber(DataSet ds)//此处的ds是已经被SqlDataAdapter.Fill(ds,"SalesOrder")处理过的;
  {
   DataSet nSet=new DataSet();//新建一个DataSet,用于把原ds里的数据倒过来;
   DataTable nTable=new DataTable("newTable");//因为是每一个数据单元都单独处理,所以用到表,以及表中的row和column对象;
   int j=0;//以后来记录ds的每一个row中有多少个column;

   foreach(DataColumn col in ds.Tables["SalesOrder"].Columns)
   {
    nTable.Columns.Add(col.Caption,typeof(string));//对新表的columns进行初始化,注意所有的column的属性都是string类型的,因为"string.format("{0:n}",number)"会把给果转成string类型
   }

   nSet.Tables.Add(nTable);
   j=ds.Tables["SalesOrder"].Columns.Count;
   foreach(DataRow row in ds.Tables["SalesOrder"].Rows)
   {
    DataRow nRow=nTable.NewRow();
    for(int i=0;i<j;i++)
    {
     if(row[i].GetType()==typeof(System.Decimal))//这里的System.Decimal由数据类型所定,如果直接用SELECT读取,多为Double型;
     {
      nRow[i]=string.Format("{0:n}",row[i]);//格式化语句,n大小写都可以;
     }
     else
     {
      nRow[i]=row[i];
     }
    }
    nSet.Tables["newTable"].Rows.Add(nRow);
   }

   this.DGrep.DataSource=nSet;
   DGrep.DataBind();
  }