CommandField删除按钮显示异常

时间:2014-11-17 08:27:13

标签: c# asp.net gridview

我正在使用CommandField删除图像按钮,但它不起作用。这是我试过的一个片段:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
        GridViewRow row = (GridViewRow)((Control)e.CommandSource).NamingContainer;
        int indx = row.RowIndex;

        using (Property_dbDataContext context = new Property_dbDataContext())
        {
            if (e.CommandName == "Delete")
            {                
                var delete = (from a in context.Property_basics where a.prop_id == GridView1.Rows[indx].Cells[0].Text select a).Single();

                    delete.delete_status = 1;
                    context.SubmitChanges();
                    GridView1.DeleteRow(indx);                
            }
        }
}

的.aspx:

<asp:CommandField ButtonType="Image"  HeaderText="Delete" DeleteImageUrl="~/wp-content/themes/realia/assets/img/500px-Delete_Icon2.png" ShowDeleteButton="True" />

它显示的例外是:

  

无法转换类型为#System; Web.UI.WebControls.ContentPlaceHolder&#39;的对象输入   &#39; System.Web.UI.WebControls.GridViewRow&#39;

3 个答案:

答案 0 :(得分:0)

试试这个:

GridViewRow row = (GridViewRow)((Control)e.CommandSource).NamingContainer.Parent.Parent;

或喜欢

设置命令参数

CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" 


int index = Convert.ToInt32(e.CommandArgument);


GridViewRow row = ProductsGridView.Rows[index];

答案 1 :(得分:0)

您应该使用CommandArgument来获取RowIndex,而不是搜索该行。在CommandField的情况下,CommandArgumentRowIndex。在传递标准控件的CommandArgument的情况下,它是实际的命令参数。

int rowIndex = int.Parse(e.CommandArgument);
GridViewRow row = GridView1.Rows[rowIndex];

答案 2 :(得分:0)

您的ASPX将如下所示:

       <asp:Gridview id = Gridview1 runat = "server" DataKeyNames="ID" > 

                   

Code Behind:你可以这样做,

 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    int ID = Convert.ToInt32(dg1.DataKeys[e.RowIndex].Value.ToString());
    GridViewRow row = (GridViewRow)dg1.Rows[e.RowIndex];
   // write your code. to delete 

}