How to Bind a GridView from database

前端 未结 6 2054
梦谈多话
梦谈多话 2020-12-11 19:24

How to bind a GridView?

I want to display my table data in a gridview.

I have createed SQL table EmpDetail with columns ID, Name, Salary D

6条回答
  •  -上瘾入骨i
    2020-12-11 20:15

    In order to run this code, you need to replace connectionstring's credentials myServerName\myInstanceName, myDataBase, myUsername, myPassword with yours

    using System.Data;   
    using System.Data.SqlClient;
    
    string sConnectionString = @"Data Source=myServerName\myInstanceName;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;";
    
    protected void Page_Load(object sender, EventArgs e){
        if(!IsPostBack)
            BindGridView();   
    }
    
    private void BindGridView() {             
        DataTable dt = new DataTable();           
        SqlConnection con = null;         
    
        try {
            string sQuery = "SELECT ID, Name, Salary FROM EmpDetail";
    
            SqlConnection con = new SqlConnection(sConnectionString);
            con.Open();
            SqlCommand cmd = new SqlCommand(sQuery, con); 
            SqlDataReader sdr = cmd.ExecuteReader();
    
            dt.Load(sdr);
            Gridview1.DataSource = dt;
            Gridview1.DataBind();
        }
        catch{ }
        finally{
            dt.Dispose();
            con.Close();
        }
    }
    

提交回复
热议问题