摘要:GridView練習
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="產品ID" ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="產品名稱" SortExpression="ProductName" />
<asp:BoundField DataField="Quantity" HeaderText="品質" SortExpression="Quantity" />
<asp:BoundField DataField="Price" HeaderText="價錢" SortExpression="Price" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings: NorthwindConnection %>" SelectCommand="SELECT * FROM [Suppliers]"></asp: SqlDataSource>
GridView ID : 此ASP GridView的ID
DataKeyNames : 引入資料的主鑑值欄位名稱
DataSourceID : 引入的DataSource ID
PS: datasource宣告時 資料庫語法會跟著
ConectionString 需在Webconfig中設置(使用精靈的話會自動幫你設置)
connectionString範例, 請放在connectionStrings標籤裡
<add name="NorthwindConnection" connectionString="Data Source=CLRIS-PC\SQLEXPRESS; Initial Catalog=Northwind;User ID=sa;Password=sa"
providerName="System.Data. SqlClient" />
Columns標籤中
BoundField 為每一個資料列
DataField 填上資料庫欄位名稱
HeaderText 請填上想在網頁上顯示的欄位名稱
SortExpression="string" 可以使此欄位排序
↓某欄位加上編輯、刪除按鈕
<asp:TemplateField ItemStyle-Width="5%" HeaderText="動作">
<ItemTemplate>
<asp:Button ID="Button_review" Text="編輯" CommandName="review" runat="server" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
<asp:Button ID="Button_Delete" Text="刪除" CommandName="Delete" runat="server" CommandArgument="<%# ((GridViewRow)
Container).RowIndex %>" OnClientClick="return confirm('確定刪除嗎?');" />
</ItemTemplate>
</asp:TemplateField>
後置程式碼對應
//GV裡面的編輯按鈕
if (e.CommandName == "review")
{
}
//GridView裡面的刪除按鈕
if (e.CommandName == "Delete")
{
}
------------------------------ ------------------------------ ------------------------------ ------------------------------ ------------------------------ -------------
流程
(1)Webcofig的ConnectString
(2)SqlDataSource 使用 (1)的字串
(3)GridView使用SqlDataSource的ID