用SqlDataAdapter+DataSet SqlConnection con = new SqlConnection(); con.ConnectionString ="server=(local);uid=sa;pwd=sa;database=Northwind;"; SqlCommand cmd = new SqlCommand(); cmd.CommandText = "select * from Employees"; cmd.Connection = con; SqlDataAdapter sda = new SqlDataAdapter(); sda.SelectCommand = cmd; con.Open();//打开数据库连接 DataSet ds = new DataSet(); sda.Fill(ds, "Employees");//用Employees表填充数据集 con.Close();//关闭数据库连接 this.GridView1.DataSource = ds; this.GridView1.DataBind(); 用SqlDataReader SqlConnection con = new SqlConnection ConnectionString ="server=(local);uid=sa;pwd=sa;database=Northwind;"; SqlCommand cmd = new SqlCommand(); cmd.CommandText = "select * from Employees"; cmd.Connection = con; con.Open();//打开数据库连接 SqlDataReader sdr = cmd.ExecuteReader(); this.GridView1.DataSource = sdr; this.GridView1.DataBind();//将数据绑定到GridView控件中 con.Close();//关闭数据库连接 |