我希望能够在单击该gridview上的删除按钮时删除一行。我有aspx页面和后面的代码以及应用程序代码。 DeletePaymentCondition运行存储过程以删除该行。但不知何故,整体代码无法正常工作
ASPX
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='table1' border="1">
<tr class='selectme'>
<td class='donthide'>row 1, cell 1</td>
<td class='hideme'>row 1, cell 2</td>
<td class='hideme'>row 1, cell 3</td>
<td class='hideme'>row 1, cell 4</td>
</tr>
<tr class='donthideme'>
<td class='dontletmehide'>row 2, cell 1</td>
<td class='dontletmehide'>row 2, cell 2</td>
</tr>
</table>
应用代码
<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();
}
答案 0 :(得分:1)
你应该执行两个不同的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注入攻击
答案 1 :(得分:0)
我得到了解决方案。我已经对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();
}