DataGrid Learning 1

Source: Internet
Author: User

Data access is the core part of any practical application, while ASP. NET provides a rich set of controls, which are well integrated with the managed data access API provided in the Common Language Runtime Library. From today on, we will learn how to use the DataGrid Data Control.
To enable the page to access the classes required for SQL Data access, you must import the System. Data and System. Data. SqlClient namespaces to the page.
<% @ Import Namespace = "System. Data" %>
<% @ Import Namespace = "System. Data. SqlClient" %>
To select a query for an SQL database, create a SqlConnection with the database, pass the connection string, construct the SqlCommand object containing the query statement, and then construct the SqlDataReader object to read data. To bind the DataGrid to data, assign the instance of the SqlDataReader object to the DataSource attribute of the DataGrid and then bind it.
The Code is as follows:
Add the DataGrid Control to the aspx file and modify the attributes as follows:
<H3> <font face = ""> simple selection of the DataGrid Control </font> <ASP: dataGrid id = "DataGrid1" runat = "server" Width = "700" BackColor = "# ccccff" BorderColor = "black" ShowFooter = "false" CellPadding = "3" CellSpacing =" 0 "Font-Name =" "Font-Size =" 8pt "HeaderStyle-BackColor =" # aaaadd "EnableViewState =" false ">
<HeaderStyle BackColor = "# AAAADD"> </HeaderStyle>
</ASP: DataGrid>
Add the following code to the aspx. cs file:
First, import the System. Data. SqlClient namespace;
Add the following code:
Private void Page_Load (object sender, System. EventArgs e)
{
SqlConnection myConnection = new SqlConnection ("user id = sa; password =; initial catalog = pubs; data source = jeff ");
MyConnection. Open ();
SqlCommand myCommand = new SqlCommand ("select * from Authors", myConnection );
SqlDataReader dr = myCommand. ExecuteReader ();
DataGrid1.DataSource = dr;
DataGrid1.DataBind ();
MyConnection. Close ();
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.