根據自己的了解寫的, 可能會有錯誤
以前剛開始學的時候就覺得連個資料庫怎麼需要這麼多東西, 現在解釋下希望可以幫到剛開始學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>