GridView命令按钮无法删除

时间:2012-10-23 14:55:09

标签: c# events gridview

我在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";
    }
}  

1 个答案:

答案 0 :(得分:1)

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

您需要处理gridview RowDeleting方法:

protected void gvLineItems_RowDeleting(object sender, GridViewDeleteEventArgs e)

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

将此添加到您的计划中:

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