繁体   English   中英

从GridView SQL删除行

[英]delete row from gridview sql

我希望能够在单击该网格视图上的删除按钮时删除一行。 我有aspx页面和后面的代码以及应用程序代码。 DeletePaymentCondition运行存储过程以删除该行。 但是总的代码不起作用

aspx

    <asp:GridView ID="gridview1" runat="server" HorizontalAlign="left" AutoGenerateColumns="false" CssClass="table table-bordered " GridLines="None" 
        AllowSorting="True" OnRowDeleting="OnRowDeleting">  
         <Columns>
             <asp:TemplateField ItemStyle-HorizontalAlign="left" HeaderText="Payment Condition" HeaderStyle-CssClass="OGColor" HeaderStyle-ForeColor="white" SortExpression="monthToQuarters">
                <ItemTemplate>
                      <span style="font-size:12px; color: #2980b9; text-align:left">
                      <asp:Label ID="lblUserId" runat="server" Visible="true" Text="<%# bind('payConditionId')%>"/>
</span>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="150"/>           
        </Columns>
    </asp:GridView>

cs



protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        Label lblEmpID = (Label)gridPayment.Rows[e.RowIndex].FindControl("lblUserId");  //This is Table Id load on Label1

        int id = Convert.ToInt32(lblEmpID.Text.ToString());


        dsPayment = objcommission.Delete(id);
        gridPayment.DataSource = dsPayment.Tables[0];
        gridPayment.DataBind();

    }

应用程式码

public DataSet DeletePayment(int id)
{
    DataSet dsGetAllPayment;
    dsGetAllPaymentCondition = SqlHelper.ExecuteDataset(OGconnection, CommandType.Text, "Delete FROM tblPay where pay ='" + id + "'");
    return dsGetAllPayment;
}

您应该执行两种不同的SQL,一种用于删除,另一种用于选择,以检索新数据。

DELETE应该在NonQuery使用来执行,因为它不返回行(仅返回受影响的行数)。

public DataSet DeletePaymentCondition(int ids)
{
    int rowsAffected = SqlHelper.ExecuteNonQuery(OGconnection, CommandType.Text, "Delete FROM [Accounting].[dbo].[tblPayConditions] where payConditionId ='" + ids + "'");
    DataSet dsGetAllPaymentCondition = SqlHelper.ExecuteDataSet(OGconnection, CommandType.Text, "Select * FROM [Accounting].[dbo].[tblPayConditions]");
    return dsGetAllPaymentCondition;
}

作为一个好习惯,您应该考虑将其更改为参数化查询。 在这种情况下,由于整数转换是安全的,但是在带有字符串参数的类似代码中,您将容易受到SQL Injection攻击

我找到了解决方案。 我对CS文件以及bradbury9提供的代码进行了更改。

protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
    {

        int index = Convert.ToInt32(gridPaymentCondition.DataKeys[e.RowIndex].Value.ToString());

        dsPaymentCondition = objcommission.DeletePaymentCondition(index);
        gridPaymentCondition.DataSource = dsPaymentCondition.Tables[0];

        updatePaymentConditionsWithoutRefresh();
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM