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


     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();//关闭连接
            }

        }

  • 相关阅读:
    iconfont 引入后没有显示
    使用element-ui库时浏览器出现异常汉字(代码里找不到该汉字)
    ElementUI select 把整个option(对象)作为值
    不让浏览器history后退前进
    从IE浏览器链接跳转到谷歌浏览器方法
    mddir 可以生成项目工程结构
    Element-UI select 新加全部与多选互斥选择
    H5 video 常用属性
    a链接跳转报错 status为 canceled的解决办法
    学习计划与记录
  • 原文地址:https://www.cnblogs.com/yeagen/p/1330918.html
Copyright © 2020-2023  润新知