DataTable的使用

  SqlConnection con = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=Train;Integrated Security=True");
            string sql = "select * from TrainInfo where trainNum='"+txtTrainNum.Text+"'";
            SqlCommand cmd=new SqlCommand (sql,con);
            con.Open();
              SqlDataReader reader= cmd.ExecuteReader();
              DataTable dt = new DataTable("cart");
           for (int i = 0; i < reader.FieldCount; i++)//添加列头
          {

              DataColumn dc1 = new DataColumn(reader.GetName(i), Type.GetType("System.String"));
              dt.Columns.Add(dc1);//添加列
          }
       
          if (reader.Read())
         {
                    DataRow dr = dt.NewRow();//创建一个新行
                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                       
                        dr[reader.GetName(i)] = reader[i];//添加数据
                    }
                    dt.Rows.Add(dr);//把这行添加到table中
         }
          GridView1.DataSource = dt;//绑定数据
          GridView1.DataBind();//必须用这个方法
          con.Close();

posted @ 2008-11-23 20:56  华仔2008  阅读(358)  评论(0编辑  收藏  举报