ASP.NET-GridView数据绑定的几种方法
前提:頁面需要顯示多個表中的字段,幾個表之間通過字段保持聯(lián)系
方法一:直接進行級聯(lián)查詢,并將結果集通過SqlDataAdapter填充DataSet,之后將DataTable的DataView綁定到GridView的數(shù)據(jù)源,:
//連接數(shù)據(jù)庫,并獲得返回結果;
public dataset GetResult(string str1)
{
String str=“數(shù)據(jù)庫連接字符串”;
string str1=“級聯(lián)查詢語句”
SqlConneciton sconnection = new SqlConnection(str);
SqlCommand scommand = new scommand();
scommand。connection = sconnection;
scommand。textcommand = str1;
sqlDataAdapter adapter = new sqlDataAdapter();
adapter。 selectcommand = scommand;
DataSet ds = new DataSet();
adapter。fill(ds);
return ds;
}
頁面層.CS代碼Fragment:
protected void Page_Load()
{
this.GridView1.datasource = ds.tables[0].defaultView;
this.GridView1.databind();
}
頁面層。aspx文件代碼Fragment1:將dataview內的所有字段,按照dataview的次序全部綁定到頁面。
<asp:GridView id="GirdView1"></asp:GridView>
----------------------------------------------------------------
頁面層1。aspx文件代碼Fragment2:只綁定部分字段,并更換dataview的順序規(guī)則:比如在dataview內name列顯示在第三位,id顯示在第二位;而在頁面中要求不顯示id列,而只顯示name列,并排列在第二位:
<asp:GridView id=“GridView1”>
<asp:templateField>
?? <itemTemplate>
?????? <%# ((datarowview)container。dataitem)[ "name" ]。toString() %>
??? </ItemTemplate>
</asp:templateField>
<asp:templateField>
?? <itemTemplate>
????????? <%# databinder.Eval(container。Dataitem,"name") %>
?? </itemTemplate>
</asp:templateField>
<asp:templateField>
?? <itemTemplate>
????????? <%# databinder.Eval(container,"Dataitem。name") %>
?? </itemTemplate>
</asp:templateField>
</asp:GridView>
------------------------------------------------------------------------------------------------------------------------------
方法二:先取出A張表內所需要顯示的記錄,逐一賦值到n個info對象內,將所有的info對象保存在一個集合類內,(例如:List<>,dictionary,collection,arraylist,hashtable,注意這些類都是非線程安全的),之后將此集合類綁定到GirdView內。
但是一個GirdView只能綁定一個集合類,由于缺少其他表內的字段,我們必須通過A表內的ID,查詢B表內的name。所以我們需要在頁面層的CS文件,bll層,以及Dal層加入查詢name的方法:
由于Asp。net可以綁定方法,屬性,控件屬性,等等,所以這種做法是行得通的:
<asp:GridView id=“GridView1”>
<asp:templateField>
?? <itemTemplate>
?????? <%# GetName(((XXXinfo)container。dataitem)。id 。tostring())%>
??? </ItemTemplate>
</asp:templateField>
<asp:templateField>
?? <itemTemplate>
????????? <%# GetName(databinder.Eval(container。Dataitem,"name")) %>
?? </itemTemplate>
</asp:templateField>
<asp:templateField>
?? <itemTemplate>
????????? <%#?? GetName(databinder.Eval(container,"Dataitem。name") ) %>
?? </itemTemplate>
</asp:templateField>
<asp:templateField>
?? <itemTemplate>
????????? <%#?? GetName(databinder.Eval(“name”) ) %>
?? </itemTemplate>
</asp:templateField>
</asp:GridView>
//注:GetName方法被寫在頁面的。cs文件內,方法為空方法,return bll的GetName方法,之后再Return Dal的GetName方法。
------------------------------------------------------------------------------------------------------------------------------
總結:第二種方法的性能很差,因為我需要訪問兩次數(shù)據(jù)庫,而且與方法一比較會多出很多方法。
《新程序員》:云原生和全面數(shù)字化實踐50位技術專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的ASP.NET-GridView数据绑定的几种方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: node exprass安装运行实例
- 下一篇: ASP.NET 的数据绑定,DataLi