实现对gridview删除行时弹出确认对话框的方法

本文介绍如何在ASP.NET的GridView控件中实现删除操作前的确认提示。通过将CommandField转换为TemplateField并添加JavaScript确认对话框,可以有效防止误删。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1,GridView中如何使用CommandField删除时,弹出确认框? 
在VS2005提供的GridView中我们可以直接添加一个CommandField删除列:<asp:CommandField ShowDeleteButton="True" />,完后在它的RowDeleting事件中完成删除。但在多半我们在做这种删除操作时都需要先让操作者再确认下,完后再进行删除,以避免误操作引起的误删除。
可以通过下面方法给GridView删除前加上个确认对话框。
首先,在GridView的属性对框话框中点击“Columns”进入它的“字段”设计器。接着在“字段”设计器中选择以前已加上的那个CommandField“删除”列,这时在它的属性列表下会看到一个“将此它段转换为 TemplateFied”的项,点击将它转换为TemplateFied列。
完后退出该字段设计器,切换到源码视图你会发现该列已由原来的:<asp:CommandField ShowDeleteButton="True" />
变为了:

zSnap1

这样点击删除时就会先在客户端弹出“确认要删除吗?”对话框,而原来在RowDeleting事件中写的代码完全不用改变。

2.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowIndex > -1)
{
int id = Convert.ToInt32(GridView1.DataKeys[e.Row.RowIndex].Value);
LinkButton lbtnDelete = (LinkButton)e.Row.FindControl(&amp;quot;lbtnDelete&amp;quot;);
if (lbtnDelete != null)
{
lbtnDelete.CommandArgument = id.ToString();
lbtnDelete.Attributes.Add(&amp;quot;onClick&amp;quot;, &amp;quot;<script>return confirm(’是否确认删除!’)</script>&amp;quot;);
}
}
}
}

3,先引用System.windwos.Forms,然后在进行处理

zSnap2

4,添加一个删除列

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
TableCell tc = (TableCell)e.Row.Cells[e.Row.Cells.Count - 1];
for (int i = 0; i < tc.Controls.Count; i += 2)
{
// cerco il controllo ImageButton (ho utilizzato quello)
Object o = tc.Controls[i];
if (o is ImageButton)
{
// controllo trovato!
// ora aggiungo l’evento js onClick per chiedere conferma all’utente
ImageButton lb = (ImageButton) o;
((ImageButton)lb).Attributes.Add(&amp;quot;onclick&amp;quot;, @&amp;quot;javascript:return confirm(’Attenzione: sicuro di voler cancellare?’);&amp;quot;);
}
}
} zSnap3

zSnap4  zSnap5

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值