Solved

Datagrid error when paging: Index was out of range. Must be non-negative and less than the size of the collection.

Posted on 2008-10-28
4
2,401 Views
Last Modified: 2013-11-07
I have a gridview which lists people's names retrieved from a SQL database. I am assigning the row index to the image buttons' command argument when each row is created. The image buttons work fine when on the first page of data. If I go to page 2 of the gridview and click on an image button, I receive the following error:

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

Source Error:


Line 366:            Case "Notes"
Line 367:                Dim index As Integer = Convert.ToInt32(e.CommandArgument)
Line 368:                Dim selectedRow As GridViewRow = GridView1.Rows(index)
Line 369:
Line 370:                lblID = selectedRow.Cells(0).FindControl("lblID")
 

Source File: e:\inetpub\people\manage_individuals.aspx.vb    Line: 368

Stack Trace:


[ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index]
   System.Collections.ArrayList.get_Item(Int32 index) +2776637
   System.Web.UI.WebControls.GridViewRowCollection.get_Item(Int32 index) +10
   _default.GridView1_RowCommand(Object sender, GridViewCommandEventArgs e) in e:\inetpub\vs137121\pastoral-care\people\manage_individuals.aspx.vb:368
   System.Web.UI.WebControls.GridView.OnRowCommand(GridViewCommandEventArgs e) +105
   System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +76
   System.Web.UI.WebControls.GridView.OnBubbleEvent(Object source, EventArgs e) +95
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +35
   System.Web.UI.WebControls.GridViewRow.OnBubbleEvent(Object source, EventArgs e) +117
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +35
   System.Web.UI.WebControls.ImageButton.OnCommand(CommandEventArgs e) +115
   System.Web.UI.WebControls.ImageButton.RaisePostBackEvent(String eventArgument) +171
   System.Web.UI.WebControls.ImageButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5102

 


--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.42


<asp:TemplateField HeaderText="">
                        <ItemTemplate>
                           <asp:Button Text="Edit" CommandName="Edit" CausesValidation="false" runat="server" ID="btEdit" CssClass="btnClass" />
                        </ItemTemplate>
                        <EditItemTemplate>
                           <asp:Button Text="Update" CommandName="Update" CausesValidation="true" runat="server" ID="btUpdate" CssClass="btnClass" />&nbsp;
                           <asp:Button Text="Cancel" CommandName="Cancel" CausesValidation="false" runat="server" ID="btCancel" CssClass="btnClass" />
                        </EditItemTemplate>
                     </asp:TemplateField>
                    <asp:TemplateField HeaderText="Actions" HeaderStyle-Font-Bold="True" HeaderStyle-HorizontalAlign="Center">
                        <ItemTemplate>
                           <asp:ImageButton ImageUrl="/images/view_person.gif" CommandArgument='<%# Container.DataItemIndex %>' Text="Click to view details on this person" CommandName="View" runat="server" ID="ibnView" />&nbsp;
                           <asp:ImageButton imageURl="/images/remove_person.gif" CommandArgument='<%# Container.DataItemIndex %>' Text="Click to remove this person from the register" CommandName="DeletePerson" runat="server" ID="ibnDelete" />&nbsp;
                           <asp:ImageButton ImageUrl="/images/notes.gif" CommandArgument='<%# Container.DataItemIndex %>' Text="Click to view notes on this person" CommandName="Notes" runat="server" ID="ibnNotes" />
                        </ItemTemplate>
                     </asp:TemplateField>
 
Protected Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowCreated
        If e.Row.RowType = DataControlRowType.DataRow Then
 
            Dim ibn1 As ImageButton
            Dim ibn2 As ImageButton
            Dim ibn3 As ImageButton
 
            ibn1 = CType(e.Row.FindControl("ibnView"), ImageButton)
            ibn2 = CType(e.Row.FindControl("ibnDelete"), ImageButton)
            ibn3 = CType(e.Row.FindControl("ibnNotes"), ImageButton)
 
            ibn1.CommandArgument = e.Row.RowIndex
            ibn2.CommandArgument = e.Row.RowIndex
            ibn3.CommandArgument = e.Row.RowIndex
 
            ibn2.Attributes.Add("onclick", "return " & _
            "confirm('Are you sure you want to remove this person?');")
 
        End If
    End Sub

Open in new window

0
Comment
Question by:turpya
  • 2
  • 2
4 Comments
 
LVL 8

Accepted Solution

by:
tony_angelopoulos earned 500 total points
ID: 22828212
It has to do with using a template field.  You have to use the RowIndex instead.
see this post:

http://bytes.com/forum/thread601880.html
0
 

Author Comment

by:turpya
ID: 22836718
Hi,

I am doing what the article says... "To get the index, get it from current Row's RowIndex property, for example in RowCreated event".

I am using paging (AllowPaging="True"). It works on page one of the gridview, but not on any other pages - if not on page 1 and I click a button, I get the aforementioned error.

0
 
LVL 8

Expert Comment

by:tony_angelopoulos
ID: 22844374
hmmmm.... try e.row.dataitemindex  instead of row index. Paging can be a bear!
0
 

Author Comment

by:turpya
ID: 22847012
Thanks Tony.
I removed CommandArgument='<%# Container.DataItemIndex %>' from the template image buttons.

I realised I was assigning the CommandArgument twice: once in RowCreated event...
ibn3.CommandArgument = e.Row.RowIndex, the other on the image button in the gridview template.

Also removed gridview databinding from the PageIndexChanging event - not sure if this had any bearing on anything though.




0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question