根據自己的理解寫的, 可能會有錯誤
以前剛開始學的時候就覺得連個資料庫怎麼需要這麼多東西, 現在解釋下希望可以幫到剛開始學asp.net的朋友
資料擷取階段:
protected SqlConnection conn;//建立資料庫的連線物件
protected SqlDataAdapter da;//建立資料庫的查詢對象
protected DataSet ds;//建立DataSet資料表對象以實現斷開式串連
protected SqlCommand comm;//建立資料庫的操作對象
protected void Page_Load(object sender, EventArgs e)
{
conn=new SqlConnection("Data Source=localhost;Initial Catalog=nd_data;User ID=sa;Password=aaaaaa");//取連接字串, 同時建立串連
da= new SqlDataAdapter();//初始化查詢對象
da.SelectCommand= new SqlCommand("select name,id from xs Order by id,name DESC", conn);進行一個查詢id和姓名的資料庫操作
ds= new DataSet();初始化DataSet對象
try
{
conn.Open();//開啟串連
da.Fill(ds,"abs");//擷取資料,同時存放在一個名為"abs"的表中
conn.Close();//關閉串連
}
catch (SqlException e1)//錯誤處理
{
Response.Write(e1.ToString());
}
資料顯示階段:
PagedDataSource objPds= new PagedDataSource();//建立一個作用於控制項的資料來源對象
objPds.DataSource= ds.Tables["abs"].DefaultView;//傳入之前儲存的"abs"表
DataListname.DataSource= objPds;//資料來源對象傳入DataList控制項
DataListname.DataBind();//DataList控制項顯示資料資訊
前台資料顯示方法:
<ItemTemplate>//DataList資料控制項範本
<asp:Label ID="lbNwes" runat="server" Text='<%#Eval("id")%>'></asp:Label>//顯示id
<asp:Label ID="lbTime" runat="server" Text='<%#Eval("name")%>'></asp:Label>//顯示name
</ItemTemplate>