asp.net GridView中删除按钮的实现

最近遇到了GridView中按钮(ButtionField)的删除功能的实现问题,没想到一下子还不能实现,赶紧查找了一下资料然后自己实现了一下。具体内容如下:

GridView的声明:

<asp:GridView ID="GWMessage" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" Height="183px" Width="100%" OnRowDeleting="GWMessage_RowDeleting"  OnRowDataBound="GWMessage_RowDataBound" OnRowCommand="GWMessage_RowCommand">
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <Columns>
                <asp:ButtonField ButtonType="Button" CommandName="Delete"  Text="删除" />
            </Columns>
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#999999" />
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        </asp:GridView>

删除按钮功能的实现:

第一个函数

 protected void GWMessage_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //判断是否是DataRow
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //鼠标经过Row时的效果
            e.Row.Attributes.Add("onmouseover", "e=this.style.backgroundColor; this.style.backgroundColor='linen'");
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=e");
            //当点击删除按钮时激活提示
            Button btn = (Button)e.Row.Cells[0].Controls[0];
            //btn.Attributes.Add("onclick", "javascript:return confirm('你确认要删除:\"" + e.Row.Cells[1].Text + "\"吗?')");

        }


    }

注意:红色部分的代码和实现删除功能有冲突,如果没有注释掉,虽然可以弹出提示框,但是以下两个函数却不能执行了,个人还没有找到原因,还希望各位大牛指点一下。

第二个函数

 protected void GWMessage_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

    }

注意:这个函数要写,即使不用实现任何功能,它将抛出一个异常,被下面这个函数捕获。

第三s个函数

 protected void GWMessage_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int selIndex = Convert.ToInt32(e.CommandArgument);
        GridViewRow selectedRow = GWMessage.Rows[selIndex];
     
        if (e.CommandName == "Delete")
        {
            int id =int.Parse( selectedRow.Cells[1].Text.ToString());
            try
            {
                if (Socut.Data.ExecuteNonQuery("delete from Message where ID="+id)>0)
                {
                    MessageBox.Show("删除成功!");
                    RefreshDate();
               
                }
            
            }
            catch (Exception err)
            {
                MessageBox.Show("删除失败 \n" + err.Message);
            }
        }

注意:Socut.Data是一个数据访问组件,使用很方便,网上有相关介绍。

最后,虽然删除按钮的功能实现了,但是缺少了删除前的弹出确认框,如果有大牛知道怎样解决,请指导一下,谢谢。

仅此而已
原文地址:https://www.cnblogs.com/yuananyun/p/1845176.html