【问题标题】:GridView Command Button Unable to DeleteGridView 命令按钮无法删除
【发布时间】:2012-10-23 14:55:08
【问题描述】:

我在我的 GridView 中添加了一个删除命令按钮,但是每当我点击按钮时,我都会收到一个错误:

  • [HttpException (0x80004005): GridView 'GridView1' 触发了未处理的事件 RowDeleting。]
  • System.Web.UI.WebControls.GridView.OnRowDeleting(GridViewDeleteEventArgs e) +1463321

但我不知道我应该使用什么事件以及删除和编辑什么,这是我的代码:

            <asp:TemplateField HeaderText="">
                 <ItemTemplate>
                   <asp:Button ID="lkDelte" runat="server" OnClientClick="return confirm('Are you sure you want to delete?')"
                                CommandName="Delete" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>'></asp:Button>
                   </ItemTemplate>
            </asp:TemplateField>






protected void gdCourse_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Delete")
    {
        int index = Convert.ToInt32(e.CommandArgument);

        GridViewRow row = GridView1.Rows[index];

        string con_str = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(con_str);

        SqlCommand com = new SqlCommand("dbo.delete_documents", con);
        com.CommandType = CommandType.StoredProcedure;
        SqlParameter pDocument_ID = new SqlParameter("@document_id", row);

        com.Parameters.Add(pDocument_ID);

        con.Open();
        com.ExecuteNonQuery();
        con.Close();

    }
    else
    {
        Label2.Text = "Unable to delete";
    }
}  

【问题讨论】:

    标签: c# events gridview


    【解决方案1】:

    您的代码没有问题,但您忘记处理网格视图的RowDeleting 事件。

    你需要处理gridviewRowDeleting方法:

    protected void gvLineItems_RowDeleting(object sender, GridViewDeleteEventArgs e)

    在这种情况下,您可以在此方法中重新绑定或将方法留空,但添加它的签名以便事件可以正确触发。

    将此添加到您的程序中:

    protected void NameOfYourGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
     {
      //bind your grid view here...
     }
    

    【讨论】:

    • 对不起,你的意思是我应该删除protected void gdCourse_RowCommand(object sender, GridViewCommandEventArgs e)并添加protected void gvLineItems_RowDeleting(object sender, GridViewDeleteEventArgs e),包括里面的代码???
    • 不,您不应该删除任何内容,您需要 RowCommand 触发操作类型,在您的情况下是“删除”。您需要 RowCommand 和 RowDeleting。为删除调用 RowCommand,但您需要处理已删除行的 RowDeleting。这可以是一个空函数,但编译器需要签名,所以只需添加签名。
    • 很好,现在没有显示错误,但问题是它不会删除记录,我应该使用 标签,,,,我的意思是指定我的意思是我应该添加哪个事件 OnRowCommand = "" OnRowDeleting = "" 在 GridView 标记中
    • 您必须重新绑定您的网格,这就是为什么,向您的事件显示您添加了 RowDeleting 事件。您必须重新绑定网格,此外,Dataset ds = GetYourData(); myGrid.DataSource=ds; myGrid.DataBind(); 这应该都在 rowdeleting 事件中。
    • 我是 ASP.NET 和 C# 的新手。我很抱歉,但我真的不明白你所说的重新绑定是什么意思,你或任何人都可以给我看代码吗?我只是需要帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    • 1970-01-01
    相关资源
    最近更新 更多