我有一个asp页面,通过选择复选框然后按批准按钮批准列表的状态,但是当我选择多个复选框时,它会抛出错误:索引超出范围。我在做什么可能是错的?以下是我的代码。
<asp:GridView ID="gv2"
CssClass="table table-striped table-bordered bootstrap-datatable datatable"
runat="server" AutoGenerateColumns="false"
EmptyDataText="No records found"
OnRowDeleting="gv2_RowDeleting"
DataKeyNames="cancelinvoiceid"
AllowPaging="True"
PageSize="10"
OnPageIndexChanging="gv2_PageIndexChanging">
<Columns>
<asp:TemplateField HeaderText="Approval">
<ItemTemplate>
<asp:CheckBox ID="CheckBox" runat="server" />
<asp:HiddenField ID="hdcancelinvoiceid" runat="server" Value='<%# Eval("cancelinvoiceid") %>'></asp:HiddenField>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Account No" DataField="account_number"></asp:BoundField>
<asp:TemplateField HeaderText="Bill Ref">
<ItemTemplate> <%#Eval("yearref")%>/<%#Eval("monthref")%>-<%#Eval("referencecount")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="New Reading">
<ItemTemplate>
<asp:Label ID="lblApproved1" runat="server" Text='<%# Eval("new_reading") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Reading">
<ItemTemplate>
<asp:Label ID="lblApproved2" runat="server" Text='<%# Eval("last_reading") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField> <asp:TemplateField HeaderText="Requested By">
<ItemTemplate>
<asp:Label ID="lblRequestedBy" runat="server" Text='<%# Bind("staff_name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Reading Date">
<ItemTemplate>
<asp:Label ID="lblFirstApprovedBy" runat="server" Text='<%# Bind("created_on") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle CssClass="bottomPaging" HorizontalAlign="Center" />
</asp:GridView>
<asp:Button ID="btnFirstApprove" OnClick="FirstApprove_Click" Text="Approve" runat="server" />
<asp:Button ID="btnFirstDisApprove" CssClass="disapprove" OnClick="FirstDisApprove_Click" Text="Disapprove" runat="server" />
protected void FirstApprove_Click(object sender, EventArgs e)
{
bool success = false;
foreach (GridViewRow gvr in gv2.Rows)
{
if (gvr.RowType == DataControlRowType.DataRow)
{
CheckBox cb = (CheckBox)(gvr.FindControl("CheckBox"));
if (cb.Checked == true)
{
int cancelinvoiceid = Convert.ToInt32(gv2.DataKeys[gvr.RowIndex].Values["cancelinvoiceid"].ToString());
force_revisit obj = db.force_revisit.First(x => x.Id == cancelinvoiceid);
obj.approved_first_by = Convert.ToInt32(Session["CreatedBy"]);
obj.approved_first_on = Convert.ToDateTime(DateTime.Today);
obj.approved = true;
int reading_id = obj.reading_id;
reading rx = db.readings.First(x => x.Id == reading_id);
rx.force_revisit = false;
db.SaveChanges();
Bindgv2();
success = true;
}
}
}
if (success)
{
lblMessage.InnerHtml = "Approved successfully.";
lblMessage.Attributes["class"] = "alert alert-success";
}
}