In ASP. there are two methods to access the SQL Server database in. NET: System. data. oleDb and System. data. sqlClient. the following program uses System. data. sqlClient is used as an example to access the local database server.
First, import the namespace: System. Data and System. Data. SqlClient. For detailed code, see the source program.
<% @ Import Namespace = "System. Data" %>
<% @ Import Namespace = "System. Data. SqlClient" %>
<Html>
<Script language = "C #" runat = "server">
Protected void Page_Load (Object Src, EventArgs E)
{
SqlConnection myConn = new SqlConnection ("server = localhost; uid = sa; pwd =; database = pubs ");
// Create the object SqlConnection
String strSQL = "SELECT au_id, au_lname, au_fname, phone, address, city, zip FROM authors ";
SqlDataAdapter myCmd = new SqlDataAdapter (strSQL, myConn );
// Create the object SqlDataAdapter
DataSet ds = new DataSet ();
// Create an object DataSet
MyCmd. Fill (ds );
// Fill in data to Dataset
DataView source = new DataView (ds. Tables [0]);
MyDataGrid. DataSource = source;
MyDataGrid. DataBind ();
// Bind data to the DataGrid
}
</Script>
<Body>
<H3> <font face = "Verdana"> Simple SELECT to a DataGrid Control
</Font> <ASP: DataGrid id = "MyDataGrid" runat = "server"
Width = "600"
BackColor = "# ccccff"
BorderColor = "black"
ShowFooter = "false"
CellPadding = 3
CellSpacing = "0"
Font-Name = "Verdana"
Font-Size = "8pt"
HeaderStyle-BackColor = "# aaaadd"
MaintainState = "false"
/>
</Body>
</Html>