【问题标题】:Delete Row From Gridview with CommandName使用 CommandName 从 Gridview 中删除行
【发布时间】:2015-01-25 05:28:41
【问题描述】:

我正在尝试使用CommandName 从我的Gridview 中删除行,但它不起作用。我正在使用 get RowIndex 来执行此操作。

我没有收到任何错误,只是当我点击 ImageButton 时它什么也没做。

这是我的代码:

<asp:GridView ID="GridView1" runat="server" Width="538px" BackColor="White"  BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical" onselectedindexchanged="DropDownList5_SelectedIndexChanged" CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt" Font-Size="Small"  >
    <AlternatingRowStyle BackColor="White" />

    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:ImageButton ID="ImageButton1" runat="server" Height="16px" ImageUrl="~/images/delete.png" Width="16px" CommandName="DeleteRow" />
            </ItemTemplate>
            <HeaderStyle Width="30px" />
            <ItemStyle Height="10px" />
        </asp:TemplateField>
    </Columns>

    <FooterStyle BackColor="#CCCC99" />
    <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
    <RowStyle BackColor="#F7F7DE" />
    <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
    <SortedAscendingCellStyle BackColor="#FBFBF2" />
    <SortedAscendingHeaderStyle BackColor="#848384" />
    <SortedDescendingCellStyle BackColor="#EAEAD3" />
    <SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>

这是cs代码:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (Page.IsPostBack)
    {
        if (e.CommandName.Equals("DeleteRow"))
        {
            GridViewRow oItem = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
            int RowIndex = oItem.RowIndex;
            GridView1.DeleteRow(RowIndex);
            DataBind();
        }
    }
}

【问题讨论】:

标签: c# asp.net


【解决方案1】:

试试这个

我建议你从数据库中删除并再次绑定 GridView,而不是做你所做的事情

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{



    if (e.CommandName.Equals("DeleteRow"))
    {
        GridViewRow oItem = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
        int RowIndex = oItem.RowIndex;

        girdivewBind(); // Bind your gridview again. 
    }

}


public void deleteRecord(string ID)
{
  using (SqlConnection con = new SqlConnection(cn.ConnectionString))
   {
     using (SqlCommand cmd = new SqlCommand())
     {
        cmd.CommandText = "delete from Mytable where ID=@id";
        cmd.Connection = con;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@id", ID);
        con.Open();
        var temp = cmd.ExecuteNonQuery();
        con.Close();
       }
   }
 }

【讨论】:

  • 我无法从数据库中删除它
【解决方案2】:

试试这个:

GridView:

<ItemTemplate>
   <asp:ImageButton CommandName="DeleteProduct" ID="ImageButton1" runat="server" CausesValidation="false"    " ImageUrl="~/Admin/Images/SendToShop.png"/>
</ItemTemplate>

C#

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "DeleteProduct")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            GridViewRow row = grdCart.Rows[index];

            int productId = int.Parse(((Label)GridView1.Rows[row.RowIndex].FindControl("lbProdId")).Text);

            DeleteProduct(productId);
       }
    }

private void DeleteProduct (int productID)
    {
        //delete the product
    }

【讨论】:

    【解决方案3】:

    如果您还想从数据库中删除该行并将更改反映在页面上,请使用GridViewID_RowCommand

    aspx

        <asp:GridView ID="GridView1" runat="server"
    onselectedindexchanged="DropDownList5_SelectedIndexChanged"
    CssClass="mGrid"
    PagerStyle-CssClass="pgr"
    AlternatingRowStyle-CssClass="alt" >
    
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:ImageButton ID="ImageButton1" runat="server"
         Height="16px" ImageUrl="~/images/delete.png"
        CommandName="DeleteRow" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    

    C#

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "DeleteRow")
            {
               int index = Convert.ToInt32(e.CommandArgument);
               GridViewRow selectedRow = GridView1.Rows[index];
               string id = selectedRow.Cells[0].Text; //assuming your ID is the first column of your grid
               SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString); //assuming your connection string is in web.config
               con.Open();
               SqlCommand sq = new SqlCommand("DELETE FROM myTable where id='" + id + "'", con);
               sq.ExecuteNonQuery();
               con.Close();
            }
    
        }
    

    如果您不记得ID 的列索引,您仍然可以通过Grid Header follow this answer 的名称获取ID

    在您的页面加载中

    protected void Page_Load(object sender, EventArgs e)
        {
            if(this.IsPostBack)
           { 
            SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString);
            con.Open();
            SqlCommand sqlCommand = new SqlCommand("SELECT * FROM myTable",con);
            SqlDataReader reader = sqlCommand.ExecuteReader();
            GridView1.DataSource = reader;
            GridView1.DataBind();
            con.Close();
         }
       }
    

    编辑:网格不应该绑定在PostBack,我建议不要这样做。更新不在Page_Load 中的gridview,而是将GridView 包装在UpdatePanel

    <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
                  <ContentTemplate>
    
      <asp:GridView ID="gv1" ...> ... </asp:GridView>
    
                     </ContentTemplate>
              </asp:UpdatePanel>
    

    然后在需要更新网格的任何地方调用UpdatePanel2.Update()(在这种情况下,您需要在修改其源的网格BindRowCommand 并在绑定后调用UpdatePanel2.Update()

    记住无论你做什么,你都不能停止PostBack,因为点击是在按钮上。

    【讨论】:

      【解决方案4】:

      我在运行时在 Gridview 中完成了行删除,而没有删除数据表中的记录。请在下面找到代码。

      我的网格视图

      <asp:GridView ID="grdAddEditDefectParameterDetails" runat="server" OnRowDataBound="grdAddEditDefectParameterDetails_RowDataBound" OnRowDeleting="grdAddEditDefectParameterDetails_RowDeleting" >
      <Columns>
          <asp:BoundField DataField="DEFECT_PARAM_CODE" HeaderStyle-CssClass="headTb4" Visible="false"
              HeaderText="Defect No.">
              <ItemStyle Wrap="False" />
          </asp:BoundField>
          <asp:TemplateField HeaderStyle-CssClass="headTb4" HeaderStyle-Width="5%" HeaderText="Select">
              <ItemTemplate>
                  <asp:CheckBox ID="ChkStatus" runat="server" AutoPostBack="true" DataTextField="ACTIVE"
                      onclick="javascript:return OnChange(this);" />
                  <asp:HiddenField ID="idDefectParam" runat="server" Value='<%# Eval("DEFECT_PARAM_CODE") %>' />
              </ItemTemplate>
              <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="5%" />
          </asp:TemplateField>
          <asp:BoundField DataField="DEFECT_PARAM_DESCRIPTION" ItemStyle-Width="44%" HeaderStyle-CssClass="headTb4"
              HeaderText="Defect Parameter Description" HtmlEncode="false">
              <ItemStyle Wrap="False" />
          </asp:BoundField>
          <asp:TemplateField HeaderText="Penalty Applicable" HeaderStyle-Width="7%" HeaderStyle-CssClass="headTb4">
              <ItemTemplate>
                  <asp:CheckBox ID="ChkPenalty" Enabled="false" runat="server" DataTextField="PENALTY_APPLICABLE"></asp:CheckBox>
              </ItemTemplate>
              <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="7%" />
          </asp:TemplateField>
          <asp:TemplateField HeaderStyle-CssClass="headTb4" HeaderText="Defect Weightage" HeaderStyle-Width="7%">
              <ItemTemplate>
                  <asp:TextBox ID="txtAddDefectWeightage" runat="server" CssClass="inputSmallGrid"
                      MaxLength="6" onkeypress="javascript:return isNumericKey(event);" Text="0.00"
                      AutoCompleteType="Disabled"></asp:TextBox>
              </ItemTemplate>
              <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="7%" />
          </asp:TemplateField>
      
      </Columns>
      

      在您的 .cs 文件中添加以下函数

      protected void grdAddEditDefectParameterDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
          {
      
          }
      

      然后写下面的代码来删除行

      grdAddEditDefectParameterDetails.DeleteRow(grdAddEditDefectParameterDetails.Rows[i].RowIndex);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-05-25
        • 2016-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-21
        相关资源
        最近更新 更多