DataTable .Load 方法 (IDataReader)
DataTable .Load 方法 (IDataReader)用来从DataReader对象中填充DataTable所需的数据
1 public DataTable GetAllInventory() 2 { 3 // Prep command object. 4 string sql = "Select * From Inventory"; 5 SqlCommand cmd = new SqlCommand(sql, this.sqlCn); 6 SqlDataReader dr = cmd.ExecuteReader(); 7 8 // This will hold the records. 9 DataTable inv = new DataTable(); 10 11 // Fill the DataTable with data from the reader and clean up. 12 //通过所提供的 IDataReader,用某个数据源的值填充 DataTable。 如果 DataTable 已经包含行,则从数据源传入的数据将与现有的行合并。 13 inv.Load(dr); 14 //也可以用dr循环获取数据并赋值给DataRow 15 dr.Close(); 16 return inv; 17 }
以前没用过这个函数。
如果不这么做,就得这么操作了(未经测试,见谅)。
1 DataTable dt = new DataTable(); 2 dt.Columns.Add("col1"); 3 dt.Columns.Add("col2"); 4 while (dr.Read()) 5 { 6 DataRow row=new DataRow(); 7 row["col1"] = dr["col1"]; 8 row["col2"] = dr["col2"]; 9 dt.Rows.Add(row); 10 } 11 dt.AcceptChanges();