ASP.NET控件(gridview datalist等等 )后台绑定数据

以Gridview为例:

    string sql = string.Format("SELECT * from table");  //定义sql检索语句
    SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());//数据库连接字符串
    SqlCommand command = new SqlCommand(sql, connection);   //命令
    DataSet ds = new DataSet();      //定义dataset对象
    connection.Open();//连接数据库
    SqlDataAdapter da = new SqlDataAdapter(sql, connection);//定义SqlDataAdapter
    da.Fill(ds); //将获得的数据填充到ds中
    connection.Close();//连接关闭
    GridView GridView1 = (GridView)e.Item.FindControl("GridView1");//获得前台控件GridView1
    GridView1.DataSource = ds;
    GridView1.DataBind();//数据绑定

你可能感兴趣的:(asp-net)