900 likes | 1.11k Views
第 21 章 資料連結控制項與資料庫整合應用. 資料連結控制項. 顯示資料庫的資料 利用 Response.Write() 把字串內容( HTML 語法) 需要迴圈的控制 可以製作複雜的表格、 debug 相對容易 利用資料連結控制項( data-bound controls ) 程式碼相對簡單許多,但是想了解 .NET 的每一個用法不容易 只適合製作簡單的表單呈現(?),製作複雜表單反而更難。 有第 5 章的 CheckBoxList 、 RadioButtonList 、 DropDownList 等
E N D
資料連結控制項 • 顯示資料庫的資料 • 利用 Response.Write() 把字串內容(HTML 語法) • 需要迴圈的控制 • 可以製作複雜的表格、debug 相對容易 • 利用資料連結控制項(data-bound controls) • 程式碼相對簡單許多,但是想了解 .NET 的每一個用法不容易 • 只適合製作簡單的表單呈現(?),製作複雜表單反而更難。 • 有第 5 章的 CheckBoxList、RadioButtonList、DropDownList 等 • 還有本章即將介紹的Repeater、DataList、GridView、和 DetailsView
資料連結控制項 • Repeater • 利用樣板告訴 Repeater 顯示 • DataList • 與 Repeater 類似,而且支援編輯和刪除功能 • 以 Item(一列資料)為設計主軸 • GridView • 除了 DataList 的功能之外,還有分頁、排序 • 以 Column 為設計主軸 • DetailsView • 一次只顯示一筆資料,具有分頁、更新、新增、與刪除的功能 • 以 Field 為設計主軸 • 可以和 GridView 搭配使用 • DataGrid • 與 GridView 類似,為 .NET 1.x 的元件
資料連結控制項 • 控制項大多具有 DataSource 的屬性 • 讓我們以第 5 章的 CheckBoxList 為例 <asp:CheckBoxList runat="server" ID="…" AppendDataBoundItems="{True|False}"AutoPostBack="{True|False}" CellPadding="n" CausesValidation="{True|False}" DataSource="<%# … %>" CellSpacing="n" DataMember="…" DataSourceID="…" DataTextField="…" DataValueField="…" RepeatColumns="n" DataTextFormatString="…" Text="…" ValidationGroup="…" RepeatDirection="{Vertical|Horizontal}" RepeatLayout="{Flow|Table}" TextAlign="{Right|Left}" OnSelectedIndexChanged="…" OnTextChanged="…"> <asp:ListItem Enabled="{True|False}" Value="…" Selected="{True|False}" Text="…" /> </asp:CheckBoxList>
\Ch05\CheckBoxList.aspx 01:<%@ Page Language="VB" %> 02:<script runat="server"> 03: Sub btnOK_Click(ByVal sender As Object, ByVal e As System.EventArgs) 04: Dim I As Integer, Msg As String = "您選擇了:" 05: For I = 0 To Fruit.Items.Count - 1 06: If Fruit.Items(I).Selected Then 07: Msg = Msg & Fruit.Items(I).Value & "" 08: End If 09: Next 10: Message.Text = Msg 11: End Sub
12:</script> 13: 14:<html> 15: <body> 16: <form runat="server" id="form1"> 17: 您最喜愛的水果有: <br /> 18: <asp:CheckBoxList ID="Fruit" runat="server" RepeatDirection="Horizontal"> 19: <asp:ListItem Text="草莓" Value="草莓" /> 20: <asp:ListItem Text="西瓜" Value="西瓜" /> 21: <asp:ListItem Text="鳳梨" Value="鳳梨" Enabled="False" />
22: <asp:ListItem Text="香蕉" Value="香蕉" /> 23: <asp:ListItem Text="櫻桃" Value="櫻桃" /> 24: </asp:CheckBoxList> 25: <asp:Button runat="server" ID="btnOK" Text="確定" OnClick="btnOK_Click" /> 26: <br /><br /><asp:Label runat="server" ID="Message" ForeColor="Red" /> 27: </form> 28: </body> 29:</html>
讓 CheckBoxList 使用 DataSource • 步驟一:宣告 asp:CheckBoxList <asp:CheckBoxList ID="mychecklist" runat="server" DataTextField="bookname" DataValueField="bookname" AutoPostBack="True"> </asp:CheckBoxList> • DataTextField: 取得資料來源(資料庫)的欄位名稱,而形成 asp:ListItem 的 Text 屬性值 • DataValueField:取得資料來源的欄位值,而形成 asp:ListItem 的 Value 屬性值 • asp:ListItem 的資料從資料庫而來 • AutoPostBack 在第 11 章說明
讓 CheckBoxList 使用 DataSource • 步驟二:為 asp:CheckBoxList 建立 DataSource Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) '與資料庫連線 Dim database = "DSN=Bob" Dim conn As New OdbcConnection( database ) conn.Open() Dim sql As String = "Select bookname from books" Dim datareader As OdbcDataReader Dim cmd As New OdbcCommand(sql,conn) datareader=cmd.ExecuteReader() '連繫資料 mychecklist.DataSource = datareader mychecklist.DataBind() End Sub
再試試看:RadioButtonList • RadioButton 控制項用來建立選項按鈕,其宣告語法如下: <asp:RadioButton runat="server" ID="…" AutoPostBack="{True|False}"CausesValidation="{True|False}" Checked="{True|False}" GroupName="…" Text="…" TextAlign="{Right|Left}" ValidationGroup="…" OnSelectedIndexChanged="…" />
再試試看:RadioButtonList • 步驟與之前的類似 • 這一次我們試一下 OnSelectedIndexChanged 的屬性 <asp:RadioButtonList ID="mylist" runat="server" RepeatDirection="Horizontal" DataTextField="bookname" DataValueField="bookname" AutoPostBack="True" OnSelectedIndexChanged="item_click"> </asp:RadioButtonList> Sub item_click(ByVal sender As Object, ByVal e As System.EventArgs) Dim msg as String = "你喜歡閱讀:" msg = msg & mylist.selecteditem.value label1.Text = msg End Sub
練習題 • 請利用 DropDownList 來完成之前的圖書資料修改的工作 • 請利用 DropDownList 完成 • 選擇”台北市”或者”台中市” • 若台中市被選擇,則區域的選擇就會出現”中區”、“南屯區”等
Repeater 控制項 <asp:Repeater runat="server" ID="…" DataMember="…" DataSource="<%# … %>"DataSourceID="…" OnItemCommand="…" OnItemCreated="…" OnItemDataBound="…"> <AlternatingItemTemplate> 替代項目樣板,可以包含 HTML 標籤、伺服器控制項… </AlternatingItemTemplate> <FooterTemplate> 頁尾樣板,可以包含 HTML 標籤、伺服器控制項… </FooterTemplate> <HeaderTemplate> 頁首樣板,可以包含 HTML 標籤、伺服器控制項… </HeaderTemplate>這個部份為樣板,用來定義 Repeater 控制項各區域的內容,其中只有 ItemTemplate 為必要樣板,其它樣板都可以省略。 <ItemTemplate> 一般項目樣板,可以包含 HTML 標籤、伺服器控制項… </ItemTemplate> <SeparatorTemplate> 分隔樣板,可以包含 HTML 標籤、伺服器控制項… </SeparatorTemplate> </asp:Repeater>
Repeater 控制項 • Repeater 控制項提供下列五種樣板,用來定義各區域的內容: • AlternatingItemTemplate • FooterTemplate • HeaderTemplate • ItemTemplate • SeparatorTemplate
Repeater 控制項 • Repeater 控制項用來控制資料輸出的是「一般項目樣板」及「替代項目樣板」,那麼要如何將連結至 Repeater 控制項的資料顯示出來呢?很簡單,只要在一般項目樣板或替代項目樣板加入下列語法即可,其中格式字串可以省略: • 格式字串的使用方式與 CheckBoxList 控制項的 DataTextFormatString 屬性相同。 <%#Eval("欄位名稱", "格式字串")%> • 細節請參考 5-32
\Ch21\Repeater_01_Access.aspx 01:<%@ Page Language="VB" %> 02:<%@ Import Namespace="System.Data" %> 03:<%@ Import Namespace="System.Data.OleDb" %> 04:<script runat="server"> 05: Sub Page_Load(sender As Object, e As System.EventArgs) 06: '取得 web.config 組態檔的資料連接設定 07: Dim setting As ConnectionStringSettings = _ ConfigurationManager.ConnectionStrings("OLEDB_Price") 08: 09: '建立資料連接 10: Dim objConn As New OleDbConnection() 11: objConn.ConnectionString = setting.ConnectionString 12: objConn.Open()
13: 14: '建立 DataReader 物件 15: Dim strSQL As String = "Select * From 零組件報價表 Where 零組件種類='印表機' Order By 廠牌 Asc" 16: Dim objCmd As New OleDbCommand(strSQL, objConn) 17: Dim objReader As OleDbDataReader = objCmd.ExecuteReader() 18: 19: '連結資料 20: myRepeater.DataSource = objReader 21: myRepeater.DataBind() 22: 23: '關閉 DataReader 物件及資料連接 24: objReader.Close() 25: objConn.Close() 26: End Sub
27:</script> 28: 29:<html> 30: <body> 31: <form id="form1" runat="server"> 32: <asp:Repeater ID="myRepeater" runat="server"> 33: <HeaderTemplate> 34: <h1>印表機報價單</h1> 35: ------------------------- 由此開始 --------------------------<br> 36: </HeaderTemplate> 37: <ItemTemplate> 38: 廠牌:<%#Eval("廠牌")%><br> 39: 規格:<%#Eval("規格")%><br> 40: 價格:<%#Eval("價格")%><br> 41: 報價日期:<%#Eval("報價日期", "{0:yyyy/MM/dd}")%><br><br> 42: </ItemTemplate>
43: <AlternatingItemTemplate> 44: <i>廠牌:<%#Eval("廠牌")%></i><br> 45: <i>規格:<%#Eval("規格")%></i><br> 46: <i>價格:<%#Eval("價格")%></i><br> 47: <i>報價日期:<%#Eval("報價日期", "{0:yyyy/MM/dd}")%></i><br> 48: </AlternatingItemTemplate> 49: <SeparatorTemplate> 50: <hr align="Left" width="200"> 51: </SeparatorTemplate> 52: <FooterTemplate> 53: ------------------------- 至此結束 ------------------------- 54: </FooterTemplate> 55: </asp:Repeater> 56: </form> 57: </body> 58:</html>
\Ch21\Repeater_03_Access.aspx (下頁續1/2) <html> <body> <form id="form1" runat="server"> <asp:AccessDataSource ID="AccessDataSource" runat="server" DataFile="~/App_Data/Price.mdb" SelectCommand="Select * From 零組件報價表 Where 零組件種類='印表機' Order By 廠牌 Asc" /> <asp:Repeater ID="myRepeater" runat="server" DataSourceID="AccessDataSource"> <HeaderTemplate> <h1>印表機報價單</h1> ------------------------- 由此開始 -------------------------<br> </HeaderTemplate>
<ItemTemplate> 廠牌:<%#Eval("廠牌")%><br> 規格:<%#Eval("規格")%><br> 價格:<%#Eval("價格")%><br> 報價日期:<%#Eval("報價日期", "{0:yyyy/MM/dd}")%><br> </ItemTemplate> <AlternatingItemTemplate> <i>廠牌:<%#Eval("廠牌")%></i><br> <i>規格:<%#Eval("規格")%></i><br> <i>價格:<%#Eval("價格")%></i><br> <i>報價日期:<%#Eval("報價日期", "{0:yyyy/MM/dd}")%>/i><br> </AlternatingItemTemplate>
<SeparatorTemplate> <hr align="Left" width="200"> </SeparatorTemplate> <FooterTemplate> ------------------------- 至此結束 ------------------------- </FooterTemplate> </asp:Repeater> </form> </body> </html>
Repeater 控制項 • 利用 Repeater 樣板顯示表格式的資料 • Header: <table> 和 table 標題 • Footer: </table> • Item: <tr><td>…</td>…</tr> • AlternatingItem: 不同的背景顏色或者配合 CSS 的 style。 • 範例:dbc03.aspx
DataList 控制項 <asp:DataList runat="server" ID="…" Caption="…"CaptionAlign="{NotSet|Top|Bottom|Left|Right}" CellPadding="n" CellSpacing="n" DataKeyField="…" DataMember="…" DataSource="<%# … %>"DataSourceID="…" EditItemIndex="n" ExtractTemplateRows="{True|False}"GridLines="{None|Horizontal|Vertical|Both}"RepeatColumns="n"HorizontalAlign="{NotSet|Left|Center|Right|Justify}"RepeatDirection="{Vertical|Horizontal}" RepeatLayout="{Flow|Table}"SelectedIndex="n" ShowFooter="{True|False}" ShowHeader="{True|False}" OnCancelCommand="…" OnDeleteCommand="…" OnEditCommand="…"OnItemCommand="…" OnItemCreated="…" OnUpdateCommand="…">
<AlternatingItemTemplate>替代項目樣板</AlternatingItemTemplate><AlternatingItemTemplate>替代項目樣板</AlternatingItemTemplate> <EditItemTemplate>編輯樣板</EditItemTemplate> <FooterTemplate>頁尾樣板</FooterTemplate> <HeaderTemplate>頁首樣板</HeaderTemplate> <ItemTemplate>一般項目樣板</ItemTemplate> <SelectedItemTemplate>選取樣板</SelectedItemTemplate> <SeparatorTemplate>分隔樣板</SeparatorTemplate> <AlternatingItemStyle … /> <EditItemStyle … /> <FooterStyle … /> <HeaderStyle … /> <ItemStyle … /> <SelectedItemStyle … /> <SeparatorStyle … /> </asp:DataList>
\Ch21\DataList_01_Access.aspx 01:<html> 02: <body> 03: <form id="form1" runat="server"> 04: <asp:AccessDataSource ID="AccessDataSource" runat="server"DataFile="~/App_Data/Address.mdb" SelectCommand="Select * From 通訊錄" /> 05: <asp:DataList ID="myDataList" runat="server" DataSourceID="AccessDataSource" BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px" Caption="通訊錄清單" CaptionAlign="Top" CellPadding="2" Width="600" HorizontalAlign="Center" RepeatColumns="2">
06: <ItemTemplate> 07: 姓名:姓名:<%#Eval("姓名")%><br> 08: 生日:生日:<%#Eval("生日", "{0:yyyy/MM/dd}")%><br> 09: 電話:電話:<%#Eval("電話") %><br><br> 10: </ItemTemplate> 11: <AlternatingItemTemplate> 12: <b><i>姓名:<%#Eval("姓名")%></i></b><br> 13: <b><i>生日:<%#Eval("生日", "{0:yyyy/MM/dd}")%> </i></b><br> 14: <b><i>電話:<%#Eval("電話")%></i></b><br><br> 15: </AlternatingItemTemplate> 16: </asp:DataList> 17: </form> 18: </body> 19:</html>
程式 <ItemTemplate> <asp:Table runat="server"> <asp:TableRow runat="server"> <asp:TableCell runat="server"> <%#Eval("id")%> </asp:TableCell> <asp:TableCell runat="server"> <%#Eval("bookname")%> </asp:TableCell> </asp:TableRow> </asp:Table> </ItemTemplate> <AlternatingItemStyle BackColor="PaleGoldenrod"/> <HeaderStyle BackColor="Tan" Font-Bold="True"/> </asp:DataList> </form> </body> </html> <html> <body> <form id="form1" runat="server"> <asp:DataList ID="mylist" runat="server" Caption="圖書管理系統“ BackColor="LightGoldenrodYellow“ ExtractTemplateRows="True“ Width="400" HorizontalAlign="center"> <HeaderTemplate> <asp:Table runat="server"> <asp:TableRow runat="server“ HorizontalAlign="center"> <asp:TableCell runat="server" Text="編號"/> <asp:TableCell runat="server" Text="書名"/> </asp:TableRow> </asp:Table> </HeaderTemplate>
使用 DataList 的修改功能 * 使用時機:如購物車內的更改數量、或刪除
使用 DataList 的修改功能 • 步驟一:定義 asp:SqlDataSource • 必須使用 ASP.NET 2.0 的新功能,data source and data-bound server controls • asp:SqlDataSource (還有其他五種) • 可以用來連結 SQL Server、OLE DB、以及 ODBC • 課本有 OLEDB 和 SQL Server 的方式,我們提供 ODBC 的方式 • 請特別注意,asp:Paramter 宣告的順序必須跟 Command 所使用的參數順序相同 <asp:SqlDataSource ID="odbc" runat="server" ProviderName="System.Data.Odbc" ConnectionString="DSN=Bob;" SelectCommand="select id, bookname From books" DeleteCommand="Delete From books Where id = ?" UpdateCommand="UPDATE books Set bookname = ? WHERE id = ?"> <DeleteParameters> <asp:Parameter Name="編號" Type="Int32" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="書名" Type="String" /> <asp:Parameter Name="編號" Type="Int32" /> </UpdateParameters> </asp:SqlDataSource>
使用 DataList 的修改功能 • 步驟二:定義 asp:DataList <asp:DataList ID="mylist" runat="server" Caption="圖書管理系統“ DataSourceId="odbc“ BackColor="LightGoldenrodYellow" ExtractTemplateRows="True" Width="400" HorizontalAlign="center" DataKeyField="id" OnEditCommand="edit" OnDeleteCommand="delete" OnUpdateCommand="update" OnCancelCommand="cancel">
使用 DataList 的修改功能 • 步驟三:在 ItemTemplate 多定義一個功能欄位(可以修改、刪除) • Edit代表編輯指令(EditCommand),不能改 • Delete代表刪除指令(DeleteCommand),也不能改 • Edit 相對應於之前的 OnEditCommand,也就是說,如果這個 LinkButton 被點選,ASP.NET 會自動呼叫 OnEditCommand 所定義的方法,也就是 edit。 • Delete 相對應於之前的 OnDeleteCommand。 <asp:TableCell runat="server"> <asp:LinkButton runat="server" CommandName="Edit" Text="編輯"/> <asp:LinkButton runat="server" CommandName="Delete" Text="刪除"/> </asp:TableCell>
使用 DataList 的修改功能 • 步驟四:新增 EditItemTemplate • Update 代表更新指令(UpdateCommand),不能改, 並相對應於之前的 OnUpdateCommand。 • Cancel 代表取消指令(CancelCommand),也不能改, 並相對應於之前的 OnUpdateCommand。 <EditItemTemplate> <asp:Table runat="server"> <asp:TableRow runat="server"> <asp:TableCell runat="server"> <%#Eval("id")%> </asp:TableCell> <asp:TableCell runat="server"> <asp:TextBox id="bookname" runat="server" Text='<%#Eval("bookname")%>' width="80"/> </asp:TableCell> <asp:TableCell runat="server"> <asp:Button runat="server" CommandName="Update" Text="更新"/> <asp:Button runat="server" CommandName="Cancel" Text="取消"/> </asp:TableCell> </asp:TableRow> </asp:Table> </EditItemTemplate>
使用 DataList 的修改功能 • 步驟五:新增需要的方法(dbc05.aspx) • 需要 edit、delete、update、cancel 四個方法 ' 進入資料編輯模式 Sub edit(ByVal source As Object, ByVal e As DataListCommandEventArgs) mylist.EditItemIndex = e.Item.ItemIndex mylist.DataBind() End Sub ' 取消編輯 Sub cancel(ByVal source As Object, ByVal e As DataListCommandEventArgs) mylist.EditItemIndex = -1 mylist.DataBind() End Sub
使用 DataList 的修改功能 ' 確定更新資料 Sub update(ByVal source As Object, ByVal e As DataListCommandEventArgs) Dim bookname As String = CType(e.Item.FindControl("bookname"), TextBox).Text odbc.UpdateParameters("書名").DefaultValue = bookname odbc.UpdateParameters("編號").DefaultValue = mylist.DataKeys(e.Item.ItemIndex) odbc.Update() mylist.EditItemIndex = -1 mylist.DataBind() End Sub ' 刪除所選的資料 Sub delete(ByVal source As Object, ByVal e As DataListCommandEventArgs) odbc.DeleteParameters("編號").DefaultValue = mylist.DataKeys(e.Item.ItemIndex) odbc.Delete() mylist.DataBind() End Sub
GridView 控制項的基本觀念 • GridView 控制項由下列五個項目所組成: • 標題 • 頁首 • 資料項目 • 頁尾 • 頁面巡覽區
GridView 控制項使用下列八個 TableItemStyle 物件定義其外觀: • AlternatingRowStyle • EditRowStyle • EmptyDataRowStyle • FooterStyle • HeaderStyle • PagerStyle • RowStyle • SelectedRowStyle
GridView 的欄位控制 • GridView 控制項是以表格的形式顯示資料,縱向代表欄位,而 GridView 控制項會顯示哪些欄位,可以透過下列三種方式來決定: • 自動產生欄位 • 手動定義欄位 • 混合式欄位
自動產生欄位 • 練習題:請改用 SqlDataSource 和 books • \Ch21\GridView_01_Access.aspx 01:<html> 02: <body> 03: <form id="form1" runat="server"> 04: <asp:AccessDataSource ID="AccessDataSource" runat="server" DataFile="~/App_Data/Grades.mdb" SelectCommand="Select 學號, 姓名, 會計, 統計, 會計 + 統計 As 總分 From 成績單" /> 05: <asp:GridView ID="GV" runat="server" DataSourceID="AccessDataSource" /> 06: </form> 07: </body> 08:</html>
手動指定欄位 • GridView 控制項有七種欄位類型,包括 BoundField、ButtonField、CheckBoxField、CommandField、HyperLinkField、ImageField、TemplateField,每種欄位類型均使用下列四種樣式物件定義欄位的外觀: • ControlStyle • FooterStyle • HeaderStyle • ItemStyle
BoundField • BoundField 欄位是為了顯示純文字資料用 • 屬性 • ApplyFormatInEditMode="{True|False}" • ConvertEmptyStringToNull="{True|False}" • DataField="…" • DataFormatString="{0:Axx}" • FooterText="…" • HeaderImageUrl="URI" • HeaderText="…" • InsertVisible="{True|False}" • NullDisplayText="…" • ReadOnly="True|False" • ShowHeader="{True|False}" • SortExpression=“…” (多欄位的話,以 , 分開) • Visible="{True|False}"