簡體   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