第 21 章 資料連結控制項與資料庫整合應用

90
第 21 第 第第第第第第第第第第第第第第第

Upload: amadis

Post on 01-Feb-2016

87 views

Category:

Documents


0 download

DESCRIPTION

第 21 章 資料連結控制項與資料庫整合應用. 資料連結控制項. 顯示資料庫的資料 利用 Response.Write() 把字串內容( HTML 語法) 需要迴圈的控制 可以製作複雜的表格、 debug 相對容易 利用資料連結控制項( data-bound controls ) 程式碼相對簡單許多,但是想了解 .NET 的每一個用法不容易 只適合製作簡單的表單呈現(?),製作複雜表單反而更難。 有第 5 章的 CheckBoxList 、 RadioButtonList 、 DropDownList 等 - PowerPoint PPT Presentation

TRANSCRIPT

第 21 章 資料連結控制項與資料庫整合應用

資料連結控制項 顯示資料庫的資料

利用 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.aspx01:<%@ 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 - 106: If Fruit.Items(I).Selected Then07: Msg = Msg & Fruit.Items(I).Value & " "08: End If09: Next10: Message.Text = Msg11: End Sub

12:</script>13:14:<html>15: <body>16: <form runat="server" id="form1">17: 您最喜愛的水果有: &nbsp;<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

讓 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 建立 DataSourceSub 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

再試試看: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 = msgEnd 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.aspx01:<%@ 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 = objReader21: 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 控制項 利用 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>

<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.aspx01:<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>

DataList

程式<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>

<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>

使用 DataList 的修改功能

* 使用時機:如購物車內的更改數量、或刪除

使用 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=" 編輯 "/> &nbsp;&nbsp; <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=" 更

新 "/> &nbsp;&nbsp; <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.aspx01:<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}"

分頁與排序

程式<%@ Page Language="VB" %><html> <body> <form id="form1" runat="server"> <asp:SqlDataSource ID="odbc" runat="server" ProviderName="System.Data.Odbc" ConnectionString="DSN=Bob;" SelectCommand="select name, bookname,

quantity From orders, books, bookstores where orders.no = bookstores.no and orders.id = books.id">

</asp:SqlDataSource> <asp:GridView ID="mylist" runat="server"

DataSourceId="odbc" CellPadding="3" GridLines="Horizontal" BackColor="White"

BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px"

AutoGenerateColumns="False" AllowPaging="True" AllowSorting="True" PageSize="5“ ShowFooter="True“> <Columns> <asp:BoundField DataField="name"

HeaderText=" 書局 " FooterText=" 書局 " NullDisplayText="--“ SortExpression="name"/>

<asp:BoundField DataField="bookname" HeaderText=" 書名 "

FooterText=" 書名 " NullDisplayText="--" SortExpression="bookname"/>

<asp:BoundField DataField="quantity" HeaderText="數量 " FooterText="數量 " NullDisplayText="--" DataFormatString="{0:N}"> <ItemStyle HorizontalAlign="Right"/> </asp:BoundField> </Columns> <EmptyDataTemplate> 資料不存在 </EmptyDataTemplate> <HeaderStyle BackColor="blue" Font-Bold="True"

ForeColor="white" /> <RowStyle BackColor="#E7E7FF"

ForeColor="#4A3C8C" /> <AlternatingRowStyle BackColor="#F7F7F7" /> <EmptyDataRowStyle Font-Bold="True"

ForeColor="Red" /> <FooterStyle BackColor="#B5C7DE"

ForeColor="#4A3C8C" /> <PagerStyle HorizontalAlign="center" ForeColor="red"/> </asp:GridView> </form> </body></html>

ButtonField

ButtonField 欄位的屬性 ButtonType="{Button|Image|Link}" CausesValidation="{True|False}" CommandName="…" DataTextField="…" DataTextFormatString="{0:Axx}" ImageUrl="URI" Text="…" ValidationGroup="…"

ButtonField

\Ch21\GridView_04_Access.aspx01:<%@ Page Language="VB" %>02:<script runat="server"> ‘ 03 至 09 行可以不需要,似乎 Key 會被傳遞 ‘ 因此 asp:GridView 中的 OnRowCreated 的屬性也不需要定義10: Sub GV_RowCommand(sender As Object, e As GridViewCommandEventArgs)11: If e.CommandName = "Shopping" Then12: ’12 行不需要

13: Message.Text = " 編號 " & GV.DataKeys(e.CommandArgument).Value & " 已放入購物車 "14: End If15: End Sub16:</script>17:<html>18: <body>19: <form id="form1" runat="server">20: <asp:AccessDataSource ID="AccessDataSource" runat="server" DataFile="~/App_Data/Price.mdb" SelectCommand="Select Top 5 * From 零組件報價

表 " />21: <asp:GridView ID="GV" runat="server" AutoGenerateColumns="False" GridLines="None" CellPadding="4" DataKeyNames=" 編號 "

Width="500px" DataSourceID="AccessDataSource"

ForeColor="#333333" OnRowCommand="GV_RowCommand">

22: <Columns>23: <asp:BoundField DataField="零組件種類 " HeaderText="零組件種類 "

NullDisplayText="---" />24: <asp:BoundField DataField="規格 " HeaderText="規格 " NullDisplayText="---" />

25: <asp:BoundField DataField="價格 " HeaderText="價格 " NullDisplayText="---" >

26: <ItemStyle HorizontalAlign="Center" />27: </asp:BoundField>28: <asp:ButtonField ButtonType="Button" CommandName="Shopping" Text="放入購物車 " >29: <ItemStyle HorizontalAlign="Center" />30: </asp:ButtonField>31: </Columns>

32: <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White"HorizontalAlign="Center" />

33: <AlternatingRowStyle BackColor="White" />34: <RowStyle BackColor="#E3EAEB" /> 35: <FooterStyle BackColor="#1C5E55" Font-

Bold="True" ForeColor="White" HorizontalAlign="Center" />36: </asp:GridView>37: <p><asp:Label ID="Message" runat="server"

/></p>38: </form>39: </body>40:</html>

CheckBoxField 欄位的屬性 DataField="…" Text="…"

將可供銷售但是庫存量是 0 的按鈕 disable掉

\Ch21\GridView_05_Access.aspx01:<%@ Page Language="VB" %>02:<script runat="server">03: Sub GV_RowDataBound(sender As Object, e As GridViewRowEventArgs)04: If e.Row.RowType = DataControlRowType.DataRow

Then05: Dim Purchasable As CheckBox = CType(e.Row.Cells(0).Controls(0), CheckBox)06: Dim SGButton As Button = CType(e.Row.Cells(4).Controls(0), Button)07:08: If Purchasable.Checked And e.Row.Cells(3).Text <> "0"

Then09: SGButton.CommandArgument = e.Row.RowIndex.ToString()10: Else11: SGButton.Enabled = False12: End If

13: End If14: End Sub15:16: Sub GV_RowCommand(sender As Object, e As GridViewCommandEventArgs)17: If e.CommandName = "Shopping" Then18: Dim GV As GridView = CType(e.CommandSource,

GridView)19: Message.Text = "產品編號 " & GV.DataKeys(e.CommandArgument).Value & " 已放入購物車 "20: End If21: End Sub22:</script>23:<html>24: <body>25: <form id="form1" runat="server"> 26: <asp:AccessDataSource ID="AccessDataSource" runat="server" DataFile="~/App_Data/Product.mdb" SelectCommand="Select Top 8 * From 產品資料 " />

27: <asp:GridView ID="GV" runat="server" CellPadding="3" DataKeyNames=" 產品編號 " GridLines="Horizontal" DataSourceID="AccessDataSource" Width="500px" OnRowCommand="GV_RowCommand" AutoGenerateColumns="False" BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" OnRowDataBound="GV_RowDataBound">28: <HeaderStyle BackColor="#4A3C8C" Font-Bold="True"

ForeColor="#F7F7F7" HorizontalAlign="Center" />29: <AlternatingRowStyle BackColor="#F7F7F7" />30: <RowStyle BackColor="#E7E7FF"

ForeColor="#4A3C8C" />31: <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" HorizontalAlign="Center" />32: <Columns>33: <asp:CheckBoxField DataField=" 可供銷售 " HeaderText=" 可供銷售 ">34: <ItemStyle HorizontalAlign="Center" />35: </asp:CheckBoxField>

36: <asp:BoundField DataField="產品 " HeaderText="產品 " />37: <asp:BoundField DataField=" 單價 " HeaderText=" 單

價 ">38: <ItemStyle HorizontalAlign="Right" />39: </asp:BoundField>40: <asp:BoundField DataField=" 庫存量 " HeaderText=" 庫存

量 " >41: <ItemStyle HorizontalAlign="Right" />42: </asp:BoundField>43: <asp:ButtonField ButtonType="Button" Text="放入購物車 "

CommandName="Shopping">44: <ItemStyle HorizontalAlign="Center" />45: </asp:ButtonField>46: </Columns>47: </asp:GridView>48: <p><asp:Label ID="Message" runat="server" /></p>49: </form>50: </body>51:</html>

CommandField 欄位類型可以顯示下列四種按鈕: 「選取」按鈕 (Select Button) 「刪除」按鈕 (Delete Button) 「編輯」按鈕 (Edit Button) 「新增」按鈕 (New Button)

CommandField 欄位的屬性 CausesValidation="{True|False}" CancelImageUrl="URI" CancelText="…" DeleteImageUrl="URI" DeleteText="…" EditImageUrl="URI" EditText="…" InsertImageUrl="URI" InsertText="…" NewImageUrl="URI"

NewText="…" SelectImageUrl="URI" SelectText="…" ShowCancelButton="{True|False}" ShowDeleteButton="{True|False}" ShowEditButton="{True|False}" ShowInsertButton="True|False" ShowSelectButton="{True|False}" UpdateImageUrl="URI" UpdateText="…"

提供選取後背景顏色改變

\Ch21\GridView_06_Access.aspx<html> <body> <form id="form1" runat="server"> <asp:AccessDataSource ID="AccessDataSource" runat="server" DataFile="~/App_Data/Product.mdb" SelectCommand="Select Top 8 * From 產品資料 " /> <asp:GridView ID="GV" runat="server" CellPadding="3" DataSourceID="AccessDataSource"

GridLines="Horizontal" Width="500px" AutoGenerateColumns="False" BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px"> <HeaderStyle BackColor="#4A3C8C" Font-

Bold="True" ForeColor="#F7F7F7" HorizontalAlign="Center" /> <AlternatingRowStyle BackColor="#F7F7F7" /> <RowStyle BackColor="#E7E7FF"

ForeColor="#4A3C8C" />

<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C"

HorizontalAlign="Center" /> <Columns> <asp:CommandField SelectText=" 選取 " ShowSelectButton="True"> <ItemStyle HorizontalAlign="Center" /> </asp:CommandField> <asp:CheckBoxField DataField=" 可供銷售 " HeaderText=" 可供銷售 "> <ItemStyle HorizontalAlign="Center" /> </asp:CheckBoxField> <asp:BoundField DataField="產品 " HeaderText="產

品 " /> <asp:BoundField DataField=" 單價 " HeaderText=" 單

價 "> <ItemStyle HorizontalAlign="Right" /> </asp:BoundField>

<asp:BoundField DataField=" 庫存量 " HeaderText=" 庫存量 " >

<ItemStyle HorizontalAlign="Right" /> </asp:BoundField> </Columns> <SelectedRowStyle BackColor="#738A9C" Font-

Bold="True" ForeColor="#F7F7F7" /> </asp:GridView> </form> </body></html>

除了使用 CommandField 欄位類型顯示「選取」按鈕之外,事實上,您也可以使用 ButtonField 欄位類型達到相同的效果:預設的有: Cancel 、 Delete 、 Edit

、 Insert 、 New 、 Page 、 Select、 Sort 、 Update

<asp:ButtonField CommandName="Select" Text=" 選取 ">

<ItemStyle HorizontalAlign="Center" /></asp:ButtonField>

HyperLinkField 欄位的屬性 DataNavigateUrlFields="…" DataNavigateUrlFormatString="{0:Axx

}" DataTextField="…" DataTextFormatString="{0:Axx}" NavigateUrl="URI" Target="…" Text="…"

\Ch21\GridView_07_Access.aspx<html> <body> <form id="form1" runat="server"> <asp:AccessDataSource ID="AccessDataSource" runat="server" DataFile="~/App_Data/Price.mdb" SelectCommand="Select * From 零組件報價表 " /> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="AccessDataSource"

GridLines="Vertical" Width="600px" ForeColor="Black" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px"> <Columns> <asp:BoundField DataField="零組件種類 " HeaderText="零組件種類 " /> <asp:BoundField DataField="規格 " HeaderText="規

格 " />

<asp:HyperLinkField DataNavigateUrlFields="廠商資訊 "

DataNavigateUrlFormatString="http://{0}" DataTextField="廠商資訊 " HeaderText="廠商資訊 " DataTextFormatString="http://{0}"

Target="_blank" /> </Columns> <HeaderStyle BackColor="#6B696B" Font-

Bold="True" ForeColor="White" HorizontalAlign="Center" /> <AlternatingRowStyle BackColor="White" /> <RowStyle BackColor="#F7F7DE" /> </asp:GridView> </form> </body></html>

ImageField 欄位的屬性 AlternateText="…" ConvertEmptyStringToNull="{True|

False}" DataAlternateTextField="…" DataAlternateTextFormatString="{0:Ax

x}" DataImageUrlField="…" DataImageUrlFormatString="{0:Axx}" NullDisplayText="…" NullImageUrl="URI" ReadOnly="{True|False}"

\Ch21\GridView_08_Access.aspx<html> <body> <form id="form1" runat="server"> <asp:AccessDataSource ID="AccessDataSource" runat="server" DataFile="~/App_Data/Address.mdb" SelectCommand="Select * From 通訊錄 " /> <asp:GridView ID="GV" runat="server"

CellPadding="4" DataSourceID="AccessDataSource" GridLines="None" AutoGenerateColumns="False" Width="600px" ForeColor="#333333" DataKeyNames=" 編號 " BorderStyle="Groove"> <Columns> <asp:BoundField DataField="姓名 " HeaderText="姓名 " />

<asp:BoundField DataField="生日 " DataFormatString="{0: yyyy/MM/dd}" HeaderText="生日 " />

<asp:BoundField DataField="電話 " HeaderText="電話 " />

<asp:ImageField DataImageUrlField="照片 " HeaderText="照片 " NullDisplayText="---" DataImageUrlFormatString="~/Images/{0}" DataAlternateTextField="姓名 " DataAlternateTextFormatString="{0} 的玉照 "> <ItemStyle HorizontalAlign="Center" /> </asp:ImageField> </Columns> <HeaderStyle BackColor="#507CD1" Font-

Bold="True" ForeColor="White" HorizontalAlign="Center" /> <AlternatingRowStyle BackColor="White" /> <RowStyle BackColor="#EFF3FB" /> </asp:GridView> </form> </body></html>

21-4-4 更新與刪除資料 1. 編輯資料時,只要點按該筆資料的「編輯」按

鈕,就會進入編輯模式,讓使用者更新資料。

2. 刪除資料時,只要點按該筆資料的「刪除」按鈕,就會出現刪除確認對話方塊詢問使用者是否確定要刪除。

\Ch21\GridView_10_Access.aspx01:<%@ Page Language="VB" %>02:<script runat="server">03: Sub GV_RowCreated(sender As Object, e As GridViewRowEventArgs)04: If e.Row.RowType = DataControlRowType.DataRow And (e.Row.RowState = DataControlRowState.Normal Or e.Row.RowState = DataControlRowState.Alternate)

Then05: Dim DeleteButton As Button = CType(e.Row.Cells(0).Controls(2), Button)06: DeleteButton.Attributes.Add("OnClick",

"javascript:confirm (' 刪除的項目無法復原,請確認是否刪除第 " + (e.Row.RowIndex + 1).ToString() + " 筆資料? ')")07: End If08: End Sub09: 10: Sub GV_RowUpdating(sender As Object, e As GridViewUpdateEventArgs)

也可以是

FindControl(“ 刪除” )

11: AccessDataSource.UpdateParameters("報價日期 "). DefaultValue = Today12: End Sub13:</script>14:<html>15: <body>16: <form id="form1" runat="server">17: <asp:AccessDataSource ID="AccessDataSource" runat="server" DataFile="~/App_Data/Price.mdb" SelectCommand="Select 編號 , 廠牌 , 規格 , 價格 , 報價日期

From 零組件報價表 " DeleteCommand="Delete From 零組件報價表 Where 編號 = ?" UpdateCommand=" Update 零組件報價表 Set 廠牌 = ?, 規格 = ?, 價格 = ?, 報價日期 = ? Where 編號 = ?" >18: <DeleteParameters>19: <asp:Parameter Name=" 編號 " Type="Int32" />20: </DeleteParameters>21: <UpdateParameters>22: <asp:Parameter Name="廠牌 " Type="String" />

23: <asp:Parameter Name="規格 " Type="String" />24: <asp:Parameter Name="價格 " Type="Int32" />25: <asp:Parameter Name="報價日期 " Type="DateTime" />26: <asp:Parameter Name=" 編號 " Type="Int32" />27: </UpdateParameters>28: </asp:AccessDataSource>29: <asp:GridView ID="GV" runat="server" DataKeyNames=" 編號 " DataSourceID="AccessDataSource" PageSize="4" CellPadding="4" GridLines="Vertical" ForeColor="Black" AutoGenerateColumns="False" BackColor="White" EmptyDataText="無相關的報價 " BorderColor="#DEDFDE" BorderWidth="1px" Caption="零組件報價系統 " BorderStyle="None" OnRowCreated="GV_RowCreated" OnRowUpdating="GV_RowUpdating">30: <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" HorizontalAlign="Center" /> 31: <RowStyle BackColor="#F7F7DE" /> 32: <FooterStyle BackColor="#CCCC99" HorizontalAlign="Center" />

33: <Columns>34: <asp:CommandField CancelText=" 取消 " DeleteText=" 刪除 " EditText=" 編輯 " ShowDeleteButton="True" UpdateText=" 更新 " ShowEditButton="True" ButtonType="Button" />35: <asp:BoundField DataField="廠牌 " HeaderText="廠

牌 " />36: <asp:BoundField DataField="規格 " HeaderText="規

格 " />37: <asp:BoundField DataField="價格 " HeaderText="價

格 " />38: <asp:BoundField DataField="報價日期 " HeaderText="報價日期 " ReadOnly="True" DataFormatString="{0:yyyy/MM/dd}" />39: </Columns>40: <EditRowStyle BackColor="Yellow" />41: <AlternatingRowStyle BackColor="White" />42: </asp:GridView>43: </form>44: </body>45:</html>

DetailsView 控制項 DetailsView 控制項是唯一支援新增

的 .NET 元件 常常和 GridView 合用

DetailsView 控制項是由下列五個項目所組成: 標題 頁首 資料項目 頁尾 頁面巡覽區

程式在 21-102 頁