简体   繁体   English

GridView-遍历行时的索引范围异常

[英]Gridview - index range exception when looping through rows

I have a problem with a exception below: 我有一个以下异常的问题:

index out of range 索引超出范围

I have a GridView where each row has a CheckBox. 我有一个GridView,其中每一行都有一个CheckBox。 When I select and item in a DropDown list a certain action is performed depending on the ListItem value. 当我在下拉列表中选择项目时,将根据ListItem值执行某些操作。

protected void actionSelect_SelectedIndexChanged(object sender, EventArgs e)
{       
    GridView gv = Project_GridView;

    DropDownList ddl = (DropDownList)sender;
    int SelectValue = Convert.ToInt32(ddl.SelectedValue);
    UpdateOp(gv, SelectValue);
    dl_actionSelect.SelectedIndex = 0;
    DataBind();
}

This code is run: 此代码运行:

private void UpdateOp(GridView gv, int SelectValue)
{
    foreach (GridViewRow row in gv.Rows)
    {
        CheckBox check = (CheckBox)row.FindControl("CB_ActionSelect");
        if (check.Checked)
        {
            int rowIndex = row.RowIndex;               
            DataBind();              
            if (!(DBNull.Value == gv.DataKeys[row.RowIndex].Value)) //This line throws the exception
            {
                int original_id = Convert.ToInt32(gv.DataKeys[row.RowIndex].Value);                   
                //Op_Update
                uWeb.Data.ProjLines.Op_Update(SelectValue, original_id);
            }
        }
    }
} 

Loops through rows and finds the checked ones. 遍历行并找到选中的行。 However when more than one checkbox is selected I get: 但是,当选中多个复选框时,我得到:

ArgumentOutOfRangeException: Index is out of range ArgumentOutOfRangeException:索引超出范围

And the weird part is it seems to be random amount that can successfully run. 而奇怪的是,它似乎是可以成功运行的随机数量。 1 checked always works, 2+ is rather random sometimes it works sometimes it doesn't. 1个选中项始终有效,2+有时是随机的,有时却无效。 Something with the id for the control? 带有控件ID的内容?

GridView: 网格视图:

<asp:GridView ID="Project_GridView" runat="server" SkinID="ProdView" 
      AutoGenerateColumns="False" DataKeyNames="ROWNUMBER" CssClass="gvv"
      DataSourceID="Project_ObjectDataSource" OnRowDataBound="Project_GridView_RowDataBound"
      AllowSorting="true" Width="100%" AlternatingRowStyle-BackColor="LightGray">
    <Columns>
        <asp:TemplateField HeaderText="" ItemStyle-Width="4%">
            <ItemTemplate>
                <asp:CheckBox id="CB_ActionSelect" Text="" runat="server"/>
            </ItemTemplate>                                
        </asp:TemplateField>
    </Columns>
</asp:GridView>

You should get it like this: 您应该这样得到:

string Id = gv.DataKeys[row.RowIndex %= gv.PageSize][0].ToString();

Because, the reported error occurs when the GridView's index increases from the row count. 因为,当GridView的索引从行数开始增加时,就会发生报告的错误。

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

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