public DataTable ConvertToDataTable(SqlDataReader dataReader) { DataTable dt = new DataTable(); DataTable schemaTable = dataReader.GetSchemaTable(); try { //动态构建表,添加列 foreach (DataRow dr in schemaTable.Rows) { DataColumn dc = new DataColumn(); //设置列的数据类型 dc.DataType = dr[0].GetType(); //设置列的名称 dc.ColumnName = dr[0].ToString(); //将该列添加进构造的表中 dt.Columns.Add(dc); } //读取数据添加进表中 while (dataReader.Read()) { DataRow row = dt.NewRow(); //填充一行数据 for (int i = 0; i <schemaTable.Rows.Count; i++) { row[i] = dataReader[i].ToString(); } dt.Rows.Add(row ); row = null; } dataReader.Close(); schemaTable = null; return dt; } catch(Exception ex) { //抛出异常 throw new Exception(ex.Message ); } }