Please what's causing this “Index was out of range Must be non-negative… error”?
-
12-12-2019 - |
Question
Please can someone really tell me what's wrong with this code that I'm having this error:
System.ArgumentOutOfRangeException was caught
Message=Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
int index = Int32.Parse(e.CommandArgument.ToString());
long Id = long.Parse(gvGrid.DataKeys[index][0].ToString());
var stuobj = ctx.stockUnits.SingleOrDefault(st => st.ID == Id);
if (stuobj != null)
this.txtStockUnit.Text = stuobj.NAME;
ViewState["Id"] = Id;
In the mark up (Designer source) this is what I have:
<asp:GridView ID="gvGrid" runat="server"
OnPageIndexChanging = "gvGrid_PageIndexChanging" AutoGenerateColumns="False"
BackColor="White" CssClass = "mGrid" DataKeyNames ="Id,NAME"
OnRowCommand="gvGrid_RowCommand"
...<Columns>
<asp:BoundField DataField="NAME" HeaderText="STOCK UNIT NAME" HeaderStyle-CssClass="Headerhodder"
FooterStyle-CssClass="Headerhodder" ItemStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Left"
ItemStyle-VerticalAlign="Middle" />
<asp:TemplateField HeaderStyle-CssClass="Headerhodder" FooterStyle-CssClass="Headerhodder"
ItemStyle-HorizontalAlign="Center" ItemStyle-Width="50px"
ItemStyle-VerticalAlign="Middle">
<ItemTemplate>
<asp:ImageButton ID="imgEdit" runat="server" ImageUrl="~/img/pencil.png" CommandName="EditStockUnit" CommandArgument ='<%# Container.DataItemIndex %> '
AlternateText="Edit Stock Unit" ToolTip="Edit Stock unit record" CausesValidation="false" />
Is there anything missing here? Thanks for the assistance.
Solution
This error occurs when you try to access an element of a collection which is outside of its bounds (e.g. element 10 of a 9 element array). I'm not particularly familiar with the language you are using, but the code below looks like it uses a value which can be outside of the range of the collection gvGrid.DataKeys
.
int index = Int32.Parse(e.CommandArgument.ToString());
long Id = long.Parse(gvGrid.DataKeys[index][0].ToString());
If you perform some sort of sanity check e.g. if( index < count )
on the index which is passed in to make sure that it is not greater than the last indexable element, you shouldn't get the exception.
OTHER TIPS
It worked perfectly, just use the following line instead
string Id = gvGrid.DataKeys[index %= gvGrid.PageSize][0].ToString();
So have enjoy your coding....