将SqlDataReader 数据集转化为datatbale ,在将datatable 转化为iList

 1 public IList GetModelList(string tablename, string where)
 2          {           
 3              IList list = null;
 4              DataTable dataTable = new DataTable();
 5              string sql = "select * from " + tablename;
 6              if (where != "")
 7              {
 8                  sql += " Where " + where;
 9              }
10              try
11              {
12                  System.Data.SqlClient.SqlDataReader dr = DbHelperSQL.ExcuteReader(sql);                 
13                  for (int i = 0; i < dr.FieldCount; i++)
14                  {
15                      DataColumn mydc = new DataColumn();    //关键的一步
16                      mydc.DataType = dr.GetFieldType(i);
17                      mydc.ColumnName = dr.GetName(i);
18                      dataTable.Columns.Add(mydc);          //关键的第二步
19                  }
20                  while (dr.Read())
21                  {
22                      DataRow mydr = dataTable.NewRow();     //关键的第三步
23                      for (int i = 0; i < dr.FieldCount; i++)
24                      {
25                          mydr[i] = dr[i].ToString();
26                      }
27                      dataTable.Rows.Add(mydr);            //关键的第四步
28                      mydr = null;
29                  }
30                  dr.Close();
31                  list = dataTable as IList;
32                  return (list);
33 
34              }
35              catch (Exception ex)
36              {
37                  throw ex;
38              }            
39          }

 

posted @ 2018-08-13 18:23  往事随风_go  阅读(683)  评论(0编辑  收藏  举报