Billpeng Space

技术源自生活
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

.net链接数据库绑定到GridView上

Posted on 2008-11-10 19:50  billpeng  阅读(492)  评论(0编辑  收藏  举报
 protected void Page_Load(object sender, EventArgs e)
    {
        /*第一种,使用ADO.net DataSet连接到GridView*/
        //1.创建连接字符串和命令字符串
        string connectionString = "Data Source=127.0.0.1;Initial Catalog=Northwind;Integrated Security=True";
        string commandString = "Select * From Customers";

        //2.为SQLDataAdapter构造函数传递一个字符串
        SqlDataAdapter dataAdapter = new SqlDataAdapter(commandString, connectionString);

        //3.创建一个DataSet
        DataSet dataSet = new DataSet();

        //4.填充DataSet对象
        dataAdapter.Fill(dataSet,"Customers");
       
        //5.从DataSet中获取DataTable
        DataTable dataTable = dataSet.Tables["Customers"];

        //6.绑定到Gridview
        GridView1.DataSource = dataTable;
        GridView1.DataBind();
    }

 

    protected void Page_Load(object sender, EventArgs e)
    {
        /*第二种,使用ADO.net SqlDataRead连接到GridView*/
        //1.创建连接字符串和命令字符串
        string connectionString = "Data Source=127.0.0.1;Initial Catalog=Northwind;Integrated Security=True";
        string commandString = "Select * From Customers";

        //2.创建链接对象
        SqlConnection conn = new SqlConnection(connectionString);

        //3.创建命令对象
        SqlCommand command = new SqlCommand(commandString);

        //4.打开连接
        try
        {
            //打开连接
            conn.Open;
            //为命令附加连接
            command.Connection = conn;
            //获取Data Reader
            SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
            //绑定到GridView
            GridView1.DataSource = reader;
            GridView1.DataBind();
        }
        finally
        {
            conn.Close();//关闭连接
        }

    }