如何为gridview控件里的“删除”列添加一个确认对话框?网上众说纷纭,大致见到了三种解决方案,现归纳如下:
1、继承Web.IO里的button控件,为其实现一个IPostback的接口用于回调,具体代码之复杂,只有作者自己想体会吧……
2、在gridview的RowDataBound事件中,遍历所有子控件,若属于LinkButton类,且CommandName为“Delete”,就调用其Atributes.Add方法,添加一个onclick事件内含confirm语句,即


3、目前已知的最简洁的方法,如图,在删除按钮的那一列属性里面,把DeleteText属性设为

这个太强了,赞一个。
可问题是,.net输出的html代码如下:

仔细想了想,以前用asp直接写的删除标签是这个样子的:

之后,新的问题又来了。如果我们的CommandField中ButtonType是Button的话,这段代码就失效了。我想了下,可以通过将其转换为模板列的方式来解决。
先将该字段转换成模板,然后编辑这个模板列,选中用于删除的Button,将其onClientClick属性设为


二。
GridView模板列删除获取选择行
aspx:
<asp:TemplateField HeaderText="Delete" ShowHeader="False">
<ItemStyle ForeColor="Red" />
<ItemTemplate>
<asp:LinkButton ID="BtnDelete" runat="server" CausesValidation="False" CommandName="Delete"
Text="删除" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" OnClientClick="return confirm('确认要删除此行信息吗?')"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<ItemStyle ForeColor="Red" />
<ItemTemplate>
<asp:LinkButton ID="BtnDelete" runat="server" CausesValidation="False" CommandName="Delete"
Text="删除" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" OnClientClick="return confirm('确认要删除此行信息吗?')"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
后台可以通过int rowIndex = Convert.ToInt32(e.CommandArgument);获取行的索引值
protected void gvType_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
GridViewRow gvRow = (GridViewRow)(((LinkButton)e.CommandSource).Parent.Parent);
string strID = dt2.Rows[gvRow.RowIndex].Cell[0].Text.ToString();
}
}