将datareader转换为datatable

public static DataTable CovertDatareaderToTable(SqlDataReader dr)
    {
        DataTable SorceTable = new DataTable();
        DataTable SchemaTable=dr.GetSchemaTable();

        try
        {
            foreach (DataRow dtRow in SchemaTable.Rows)
            {
                DataColumn myColumn = new DataColumn();
                myColumn.DataType = dtRow.GetType();
                myColumn.ColumnName = dtRow[0].ToString();
                SorceTable.Columns.Add(myColumn);
            }
            while (dr.Read())
            {
                DataRow mydataRow = SorceTable.NewRow();
                for (int i = 0; i < SchemaTable.Rows.Count; i++)
                    mydataRow[i] = dr[i].ToString();
                SorceTable.Rows.Add(mydataRow);
                mydataRow = null;
            }

            SchemaTable = null;
            dr.Close();
            return SorceTable;
        }
        catch (System.Exception ex)
        {
            throw new System.Exception(ex.Message, ex);
        }
    }

posted on 2009-08-19 18:53  画一个圆圈  阅读(160)  评论(0编辑  收藏  举报

导航