在ASP.NET我們常用的GridView、DetailsView控制項,都有提供內建的刪除功能,讓Developer可以很容易的開發資料維護功能,不過內建的刪除功能在刪除前並不會提示使用者是否確認刪除,導致於按下刪除後資料就真正從資料庫被刪掉,看起來似乎不夠嚴謹,因此我們可透過JavaScript來做到確認刪除的功能,說明如下:
若您的刪除功能是以CommandField實作(如下列程式碼的第8-9列),由於CommandField沒有Button控制項的OnClientClick屬性,所以無法直接設定Javascript至刪除按鈕。
1: <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
2: DataSourceID="SqlDataSource1" onrowdatabound="GridView1_RowDataBound">
3: <Columns>
4: <asp:BoundField DataField="RegionID" HeaderText="RegionID"
5: SortExpression="RegionID" />
6: <asp:BoundField DataField="RegionDescription" HeaderText="RegionDescription"
7: SortExpression="RegionDescription" />
8: <asp:BoundField DataField="SN" HeaderText="SN" InsertVisible="False"
9: ReadOnly="True" SortExpression="SN" />
10: <asp:CommandField ShowDeleteButton="True" />
11: </Columns>
12: </asp:GridView>
解決方式是在GridView的RowDataBound事件中利用Cell的Controls屬性找到型別為LinkButton的控制項,再來設定OnClientClick屬性所要執行的JavaScript。
1: protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
2: {
3: if (e.Row.RowType == DataControlRowType.DataRow)
4: {
5: foreach (Control c in e.Row.Cells[3].Controls)
6: {
7: if (c is LinkButton)
8: {
9: LinkButton lbDel = c as LinkButton;
10: lbDel.OnClientClick = @"if (confirm('Are you sure?') == false) return false;";
11: }
12: }
13: }
14: }
另外一個更簡單的方法就是先把刪除按鈕轉成TemplateField。
轉成TemplateField前刪除按鈕為CommandField(如下圖左),轉成TemplateField後如下圖右的樣子,在自行於LinkButton上加上OnClientClick所要執行的JavaScript即可。
程式碼如下:
1: <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
2: DataSourceID="SqlDataSource1" onrowdatabound="GridView1_RowDataBound">
3: <Columns>
4: <asp:BoundField DataField="RegionID" HeaderText="RegionID"
5: SortExpression="RegionID" />
6: <asp:BoundField DataField="RegionDescription" HeaderText="RegionDescription"
7: SortExpression="RegionDescription" />
8: <asp:BoundField DataField="SN" HeaderText="SN" InsertVisible="False"
9: ReadOnly="True" SortExpression="SN" />
10: <asp:TemplateField ShowHeader="False">
11: <ItemTemplate>
12: <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
13: CommandName="Delete" Text="刪除"
14: OnClientClick="if (confirm('Are you sure?') == false) return false;">
15: </asp:LinkButton>
16: </ItemTemplate>
17: </asp:TemplateField>
18: </Columns>
19: </asp:GridView>