【问题标题】:CommandField delete button showing exceptionCommandField 删除按钮显示异常
【发布时间】:2014-11-17 08:27:13
【问题描述】:

我正在使用 CommandField 删除图像按钮,但它不起作用。这是我尝试过的sn-p:

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”类型的对象转换为类型 'System.Web.UI.WebControls.GridViewRow'。

【问题讨论】:

    标签: c# asp.net gridview


    【解决方案1】:

    您应该使用CommandArgument 来获取RowIndex,而不是搜索行。对于CommandFieldCommandArgumentRowIndex。对于标准控件上传递的CommandArgument,它是实际的命令参数。

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

    【讨论】:

      【解决方案2】:

      试试这个:

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

      或者喜欢

      设置命令参数

      CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" 
      
      
      int index = Convert.ToInt32(e.CommandArgument);
      
      
      GridViewRow row = ProductsGridView.Rows[index];
      

      【讨论】:

      • 进行了更改,但现在它抛出的异常是:“无法将 'ASP.admin_panel_master' 类型的对象转换为 'System.Web.UI.WebControls.GridViewRow'。”
      • 现在抛出:“无法将类型为 'System.Web.UI.HtmlControls.HtmlForm' 的对象转换为类型 'System.Web.UI.WebControls.GridViewRow'。”
      • @HaiderKhattak 你可以试试第二种解决方案
      • 而不是 rowcommand 为什么不在 gridview_rowdeleting 中尝试您的代码?您只需要在 gridview aspx 中传递数据键
      【解决方案3】:

      您的 ASPX 将如下所示:

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

      代码背后:你可以这样做,

       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 
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-05
        • 2017-04-05
        • 2020-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多