數(shù)據(jù)訪問(wèn)是任何實(shí)際應(yīng)用程序的核心部分,而 ASP.NET 提供了一套豐富的控件,這些控件與公共語(yǔ)言運(yùn)行庫(kù)中提供的托管數(shù)據(jù)訪問(wèn) API 很好地集成在一起。從今天開(kāi)始我們就來(lái)學(xué)習(xí)DataGrid數(shù)據(jù)控件的使用。
為了使頁(yè)能夠訪問(wèn)執(zhí)行 SQL 數(shù)據(jù)訪問(wèn)所需的類,必須將 System.Data 和 System.Data.SqlClient 命名空間導(dǎo)入到頁(yè)中。 <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> 若要對(duì) SQL 數(shù)據(jù)庫(kù)執(zhí)行選擇查詢,請(qǐng)創(chuàng)建與數(shù)據(jù)庫(kù)的 SqlConnection,傳遞連接字符串,然后構(gòu)造包含查詢語(yǔ)句的 SqlCommand 對(duì)象,再構(gòu)造SqlDataReader對(duì)象讀數(shù)據(jù)。若要讓DataGrid綁定數(shù)據(jù),則要把SqlDataReader對(duì)象的實(shí)例賦予DataGrid的DataSource屬性,然后綁定它。 代碼如下:
在aspx文件里加入DataGrid控件,修改屬性如下: <h3><font face="宋體">DataGrid 控件的簡(jiǎn)單選擇</font></h3> <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>
在aspx.cs文件里加入下面代碼: 首先導(dǎo)入System.Data.SqlClient命名空間; 再加入下面代碼: 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(); }
|
溫馨提示:喜歡本站的話,請(qǐng)收藏一下本站!