Select the Blog
WebForm page of PowerChow to add a DataGrid control DataGrid1. Manual binding of the DataGrid control to SQL Server only takes a few mouse clicks. Here is the code binding.
First add the SqlClient namespace in the namespace.
using System.Data.SqlClient;
Then create the data connection con in the page load event,
SqlConnection con=new SqlConnection();
con.ConnectionString="server=(local);database=YourDataBase;Trusted_Connection=yes";
Open data connection,
con.Open();
Create a data command com,
SqlCommand com=new SqlCommand();
com.CommandText="select * from YourTable";
com.Connection=con;
Now you can start data binding, there are many ways. The simplest is to directly use the ExecuteReader method of the data command. Data binding is to set the DataSource property of the control.
DataGrid1.DataSource=com.ExecuteReader();
You can also use the data reader SqlDataReader (you cannot use its constructor), the code is as follows:
SqlDataReader dr=com.ExecuteReader();
DataGrid1.DataSource=dr;
Of course, you can also use ADO.NET's core data sets and data adapters;
SqlDataAdapter ada=new SqlDataAdapter(com.CommandText,con);
DataSet set1=new DataSet();
ada.Fill(set1);
DataGrid1.DataSource=set1;
Finally calculate the data binding expression,
DataGrid1.DataBind();