在从 GridView 删除时轻松添加确认消息






2.83/5 (11投票s)
轻松在代码后添加确认代码,然后再从 GridView 中删除行。
引言
通常,您希望在删除行(例如,从 GridView
控件中删除行)之前向用户添加确认消息。 当然,这可以通过在 ItemTemplate
中放置一个链接并在 OnClientClick
属性中添加正确的值来轻松完成。 但是,如果您想/必须从代码后执行此操作,最终会对您的单元格索引产生依赖,并可能导致灾难性的结果。
背景
即使可以通过 Cells
集合轻松完成此操作,有一天,有人会添加/移动/删除列而不查看代码后。
使用代码
以下代码将演示如何使用一种方法自动查找删除按钮并添加必要的代码。
//
protected void gvBooks_RowDataBound(object sender, GridViewRowEventArgs e)
{
AddConfirmDelete((GridView)sender, e);
}
/// <summary>
/// If the gridview has a command field where showdeletebutton is true, then
/// it add a confirm message.
/// This function should be called in the RowDataBound event
/// </summary>
public static void AddConfirmDelete(GridView gv, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (DataControlField dcf in gv.Columns)
{
if (dcf.ToString() == "CommandField")
{
if (((CommandField)dcf).ShowDeleteButton == true)
{
e.Row.Cells[gv.Columns.IndexOf(dcf)].Attributes
.Add("onclick", "return confirm(\"Are you sure?\")");
}
}
}
}
}//