使用 asp:CommandField 实现 ASP.NET GridView 删除确认
使用 LINQ to SQL 的 asp:CommandField 实现 ASP.NET GridView 删除确认。
引言
已经有一些文章讨论了如何在 GridView
中实现 JavaScript 删除确认,我知道...,但没有一篇完全符合我的需求。我的方法可以在 asp:LinqDataSource
控制自动处理更新和删除时使用。你需要为你的数据库创建一个 LINQ DataContext
类,我想同样的原理也可以应用于其他数据源类。
实现
首先,你需要一个从 LinqDataSource
获取数据的 GridView
控制。确保指定 OnRowDataBound
属性,并使用启用了删除功能的 LinqDataSource
。
<asp:GridView ID="GridView1" runat="server" PageSize="10" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="RecordID"
DataSourceID="MyDataSource" OnRowDataBound="GridView_RowDataBound">
<Columns>
<asp:BoundField DataField="Code" HeaderText="Code" SortExpression="Code"
ItemStyle-Width="100px" />
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" ItemStyle-Width="560px"
ControlStyle-Width="560px" />
<asp:CommandField HeaderImageUrl="..\Images\DeleteImg.png" ShowDeleteButton="True"
DeleteImageUrl="..\Images\DeleteImg.png" DeleteText="Delete Record"
ItemStyle-Font-Size="8pt" ItemStyle-Width="30px" ButtonType="Image">
</asp:CommandField>
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="MyDataSource" runat="server"
ContextTypeName="MyNameSpace.MyDbDataContext"
EnableUpdate="true" EnableDelete="true" TableName="MyTable">
</asp:LinqDataSource>
除了 OnRowDataBound
之外,此控件现在应该可以实现删除功能,而无需编写任何代码。
下一步是实现 GridView_RowDataBound
函数,如下所示
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// loop all data rows
foreach (DataControlFieldCell cell in e.Row.Cells)
{
// check all cells in one row
foreach (Control control in cell.Controls)
{
// Must use LinkButton here instead of ImageButton
// if you are having Links (not images) as the command button.
ImageButton button = control as ImageButton;
if (button != null && button.CommandName == "Delete")
// Add delete confirmation
button.OnClientClick = "if (!confirm('Are you sure " +
"you want to delete this record?')) return;";
}
}
}
}
这里重要的是使用完全提供的 OnClientClick
内容(当然,消息中的措辞除外)。如果你,例如,使用了像其他许多人建议的那样 "return confirm('Are you sure you want to delete the record')"
,这意味着删除命令将永远不会发布回服务器。ASP.NET 生成/呈现的实际 onclick
函数调用(如果你遵循上面的代码)将类似于这样...
onclick="if (!confirm('Are you sure you want to delete this record?')) return;
javascript:__doPostBack('ctl00$cphMain$GridView1','Delete$9')"
你可以看到,你提供的 JavaScript 会附加 ASP.NET 的回发调用。如果你在 你的 JavaScript 中过早返回,回发将永远不会被触发。
注意:我在我的 GridView
中使用了图像作为命令按钮。如果使用文本链接作为命令按钮,请记住将类型转换为 LinkButton
类,而不是 ImageButton
类。