smhy8187

 

把Datareader转化为DataTable

我们常在用三层框架返回数据集的时候,有时需要把Datareader转化为DataTable,实现的代码如下:  

public  DataTable ConvertDataReaderToDataTable(SqlDataReader dataReader)
  {
   DataTable datatable = new DataTable();
   DataTable schemaTable = dataReader.GetSchemaTable();
   //动态添加列
   try
   {
   
    foreach(DataRow myRow in schemaTable.Rows)
    {
     DataColumn myDataColumn = new DataColumn();
     myDataColumn.DataType = myRow.GetType();
     myDataColumn.ColumnName = myRow[0].ToString();
     datatable.Columns.Add(myDataColumn);
    }
    //添加数据
    while(dataReader.Read())
    {
     DataRow myDataRow = datatable.NewRow();
     for(int i=0;i<schemaTable.Rows.Count;i++)
     {
      myDataRow[i] = dataReader[i].ToString();
     }
     datatable.Rows.Add(myDataRow);
     myDataRow = null;
    }
    schemaTable = null;
    return datatable;
   }
   catch(Exception ex)
   {
    Error.Log(ex.ToString());
    return datatable;
   }
   
  }

posted on 2007-04-11 15:16  new2008  阅读(401)  评论(0编辑  收藏  举报

导航