【问题标题】:Delete and Update Row from GridView on Image Button从图像按钮上的 GridView 删除和更新行
【发布时间】:2014-11-24 16:11:02
【问题描述】:

我想在单击 ImageButton 时从 Gridview 中删除记录。请参阅 GridView 代码供您参考:-

<asp:GridView ID="grdCSRPageData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3" AutoGenerateColumns="false" OnDataBound="grdCSRPageData_DataBound" PageSize="5" AllowPaging="true" OnPageIndexChanging="grdCSRPageData_PageIndexChanging" OnRowCommand="grdCSRPageData_RowCommand">
                <AlternatingRowStyle BackColor="#CCCCCC" />
                <Columns>
                    <asp:TemplateField ItemStyle-Width="30">
                        <ItemTemplate>
                            <asp:CheckBox ID="chkSelect" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="page_title" HeaderText="Page Title" ItemStyle-Width="30" />
                    <asp:BoundField DataField="page_description" HeaderText="Page Description" ItemStyle-Width="30" />
                    <asp:BoundField DataField="meta_title" HeaderText="Meta Title" ItemStyle-Width="30" />
                    <asp:BoundField DataField="meta_keywords" HeaderText="Meta Keywords" ItemStyle-Width="30" />
                    <asp:BoundField DataField="meta_description" HeaderText="Meta Description" ItemStyle-Width="30" />
                    <asp:BoundField DataField="Active" HeaderText="Active" ItemStyle-Width="30" />
                    <asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%">
                        <ItemTemplate>
                            <asp:ImageButton ID="btnEdit" runat="server" ImageUrl="~/images/edit.png" Width="15" Height="15" />
                            <span onclick="return confirm('Are you sure want to delete?')">
                                <asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CommandName="DeleteRow" />
                            </span>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
                            <asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
                        </EditItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>

尝试使用 GridView 的“RowCommand”属性并卡住如何删除行 见代码:-

 protected void grdCSRPageData_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "DeleteRow")
        {
            //incase you need the row index 
            int rowIndex = ((GridViewRow)((ImageButton)e.CommandSource).NamingContainer).RowIndex;
            int Id = Convert.ToInt32(e.CommandArgument);
            //followed by your code 
        }
    }

【问题讨论】:

  • 祝你好运!看来你有一个好的开始。你真的有问题吗?
  • @entropic: 我需要更新和删除 ImageButton 的代码
  • ...到目前为止,您尝试了哪些不起作用的方法?
  • @entropic:我尝试了带有 CommandName 属性的 onRowCommand,但它不起作用。 ' protected void grdCSRPageData_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "DeleteRow") { //如果你需要行索引 int rowIndex = ((GridViewRow)((ImageButton)e.CommandSource).NamingContainer) .RowIndex; int Id = Convert.ToInt32(e.CommandArgument); //后面跟着你的代码 } }' 在我的代码中写什么从表格和网格视图中删除
  • 1.您应该编辑您的问题并将该代码放在那里。 2.“不工作”是什么意思? 3. 我将在这里暗中尝试 - 但您实际上并没有定义可以在上面代码中的 ImageButton 上引用的命令名称。

标签: c# asp.net gridview


【解决方案1】:

试试这个

protected void grdCSRPageData_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "DeleteRow")
        {
            int rowIndex = ((GridViewRow)((ImageButton)e.CommandSource).NamingContainer).RowIndex;
            grdCSRPageData.Rows.RemoveAt(rowIndex);
            //delete from database
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
               int Id = Convert.ToInt32(e.CommandArgument);
               string sql = "DELETE FROM YourTable WHERE ID = @ID";
               SqlCommand cmd = new SqlCommand(sql,connection);
               cmd.Parameters.AddWithValue("@ID",Id);
               cmd.ExecuteNonQuery();
           }
        }
    }

请参阅 here 以获取有关 GridView 删除的文档。

SqlCommand 文档

更新

要从其行中获取 gridView,您可以调用此函数

public static GridView GetParentGridView(GridViewRow row)
        {

            GridView gridView = (GridView)row.NamingContainer;
            return gridView;
        }

用它在我的代码中获取gridview

替换

 grdCSRPageData.Rows.RemoveAt(rowIndex)

GetParentGridView((GridViewRow)((ImageButton)e.CommandSource).NamingContainer).Rows.RemoveAt(rowIndex)

确保只有在页面加载时没有回发时才绑定网格

protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack)
      {
        //bind the gridView
      }
    }

【讨论】:

  • 表中的数据会被删除吗?
  • 来自网格视图?是的.. 你想从数据库中删除它吗?
  • 'Rows.RemoveAt'不包含定义错误来了
  • 在“Rows.RemoveAt”处我仍然遇到同样的错误
  • 尝试检查var testGridView= GetParentGridView((GridViewRow)((ImageButton)e.CommandSource).NamingContainer)的类型让我知道
【解决方案2】:

试过这样的东西,它奏效了。:-

<asp:GridView ID="grdCSRPageData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3" AutoGenerateColumns="False" OnDataBound="grdCSRPageData_DataBound" AllowPaging="True" OnPageIndexChanging="grdCSRPageData_PageIndexChanging" DataKeyNames="Id" OnRowDeleting="grdCSRPageData_RowDeleting" OnClientClick="return confirm('Are you sure you want to delete this record?')">
                <AlternatingRowStyle BackColor="#CCCCCC" />
                <Columns>
                    <%-- <asp:TemplateField ItemStyle-Width="30">
                        <ItemTemplate>
                            <asp:CheckBox ID="chkSelect" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>--%>
                    <asp:BoundField DataField="page_title" HeaderText="Page Title" ItemStyle-Width="30" />
                    <asp:BoundField DataField="page_description" HeaderText="Page Description" ItemStyle-Width="30" />
                    <asp:BoundField DataField="meta_title" HeaderText="Meta Title" ItemStyle-Width="30" />
                    <asp:BoundField DataField="meta_keywords" HeaderText="Meta Keywords" ItemStyle-Width="30" />
                    <asp:BoundField DataField="meta_description" HeaderText="Meta Description" ItemStyle-Width="30" />
                    <asp:BoundField DataField="Active" HeaderText="Active" ItemStyle-Width="30" />
                    <asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%">
                        <ItemTemplate>
                            <%-- <asp:LinkButton ID="lbtnEdit" runat="server" CommandName="Edit" Text="Edit" />--%>
                            <asp:ImageButton ID="btnEdit" runat="server" ImageUrl="~/images/edit.png" Width="15" Height="15" />
                            <%-- <span onclick="return confirm('Are you sure want to delete?')"> -- %>
                                <%--<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" ></asp:LinkButton>--%>
                           <asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CommandName="Delete" CommandArgument='<%# Eval("Id") %>' CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" />
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
                            <asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
                        </EditItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>

另见后面的代码:-

  protected void grdCSRPageData_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        bool IsDeleted = false;
        //getting key value, row id
        int Id = Convert.ToInt32(grdCSRPageData.DataKeys[e.RowIndex].Value.ToString());
        using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "DELETE FROM tbl_Pages WHERE Id=@ID";
                cmd.Parameters.AddWithValue("@ID", Id);
                cmd.Connection = conn;
                conn.Open();
                IsDeleted = cmd.ExecuteNonQuery() > 0;
                conn.Close();
            }
        }
        if (IsDeleted)
        {
            //record has been deleted successfully!
            //call here gridview bind method and replace it..
            ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Page Succesfully deleted');window.location ='csrpage.aspx';", true); ;
            grdCSRPageData.DataBind();
        }
        else
        {
            //Error while deleting record
            Response.Write("Some error");
        }
    }

数据的绑定也应该在 '(!IsPostBack)' 方法中

【讨论】:

  • 这似乎与我在聊天中写的建议非常相似。我不明白您为什么将代码编写为您的答案,而忽略了我自己的答案
  • faby,没关系。我得到一件事,我必须在 (!IsPostBack) 中绑定 onPageLoad 上的数据。这有效..我会标记你的答案,不是问题。如果有人想详细了解,请发布
猜你喜欢
  • 2011-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-09
  • 2018-07-13
  • 1970-01-01
  • 2013-02-28
  • 2023-03-13
相关资源
最近更新 更多