Solved

Gridview throws index out of rang error on RowUpdating

Posted on 2008-06-20
2
1,283 Views
Last Modified: 2013-11-07
Hi I have the following ASP.NET page

<form id="form1" runat="server">
    <div>
        <asp:SqlDataSource  ID="SqlDataSource1" SelectCommandType="StoredProcedure"
         SelectCommand="Get_TopSearchTermsByLang" UpdateCommandType="StoredProcedure" UpdateCommand="Update_TopTermPublishStatus" runat="server" />
       
     
       
       
        <asp:DropDownList ID="DropDownList1" AutoPostBack="true" EnableViewState="true"
         OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" runat="server">
        </asp:DropDownList>
       
        <asp:GridView  ID="GridView1"   OnRowUpdating="GridView1_RowUpdating" runat="server" AutoGenerateColumns="False" >
            <Columns>
           
                <asp:BoundField DataField="ID" Visible="False" />
                <asp:BoundField DataField="SearchTerm" HeaderText="Search Term" />
                <asp:BoundField DataField="TotalCount" HeaderText="Item Count" />
       
                <asp:TemplateField>
               
                <ItemTemplate>
                    <asp:CheckBox runat="server" Id="CheckBox1" Checked='<%#Bind("PublishStatus") %>' />
                   
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:ButtonField ButtonType="Button" CommandName="Update" Text="Update" />
            </Columns>
        </asp:GridView>
       

    </div>
    </form>

As you can there is a dropdownlist and a gridview, where the contents of the gridview are filtered on the selection of the dropdownlist.  You are then able to modify the publishstatus checkbox and then click Update and the GridView should refresh databind with the changes but this breaks on the Update method.  I get 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 68:
Line 69:
Line 70:             GridViewRow selectedrow = (GridViewRow)GridView1.Rows[index];
Line 71:             Label1.Text = GridView1.Rows.Count.ToString();
Line 72:
 

Source File: c:\Program Files\Immediacy\CMS\6.0\Admin\Addins\MoogDev\TagCloudAdmin.aspx.cs    Line: 70

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) +2880797
   System.Web.UI.WebControls.GridViewRowCollection.get_Item(Int32 index) +10
   Addins_MoogDev_TagCloudAdmin.GridView1_RowUpdating(Object sender, GridViewUpdateEventArgs e) in c:\Program Files\Immediacy\CMS\6.0\Admin\Addins\MoogDev\TagCloudAdmin.aspx.cs:70
   System.Web.UI.WebControls.GridViewUpdateEventHandler.Invoke(Object sender, GridViewUpdateEventArgs e) +0
   System.Web.UI.WebControls.GridView.OnRowUpdating(GridViewUpdateEventArgs e) +133
   System.Web.UI.WebControls.GridView.HandleUpdate(GridViewRow row, Int32 rowIndex, Boolean causesValidation) +776
   System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +837
   System.Web.UI.WebControls.GridView.RaisePostBackEvent(String eventArgument) +199
   System.Web.UI.WebControls.GridView.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) +177
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1746

 
Please help I'm confused why this is happening.  why is it Updating twice?

private SqlDataSource langDS;
 
 

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            langDS = new SqlDataSource();

            langDS.ConnectionString = new iSession().ConnectionString;

            langDS.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;

            langDS.SelectCommand = "immsp_cms_MultiLanguage_GetLanguages";
 

            DropDownList1.DataSource = langDS;

            DropDownList1.DataTextField = "Name";

            DropDownList1.DataValueField = "StringValue";

            

            DropDownList1.DataBind();

            //string[] langvalarray;

            foreach (ListItem item in DropDownList1.Items)

	        {

                item.Value = item.Value.Split('!')[0];

	        }

            SqlDataSource1 = new SqlDataSource();

            SqlDataSource1.ConnectionString = new iSession().ConnectionString;

            SqlDataSource1.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;

            SqlDataSource1.SelectCommand = "Get_TopSearchTermsByLang";

            SqlDataSource1.SelectParameters.Clear();

            SqlDataSource1.SelectParameters.Add("lang", "en");
 

            GridView1.DataSource = SqlDataSource1;

            GridView1.DataBind();
 

        }

        DropDownList1.SelectedIndexChanged += new EventHandler(DropDownList1_SelectedIndexChanged);

        GridView1.RowCommand += new GridViewCommandEventHandler(GridView1_RowCommand);

        GridView1.RowUpdating += new GridViewUpdateEventHandler(GridView1_RowUpdating);

    }
 

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

    {

int index = e.RowIndex;
 

                        GridViewRow selectedrow = (GridViewRow)GridView1.Rows[index];

    
 
 

            SqlDataSource1 = new SqlDataSource();

            SqlDataSource1.ConnectionString = new iSession().ConnectionString;

       

            SqlDataSource1.UpdateParameters.Clear();

            SqlDataSource1.UpdateParameters.Add("termid", (string)selectedrow.Cells[0].ToString());

            SqlDataSource1.UpdateParameters.Add("pubbool", (string)selectedrow.Cells[3].ToString());
 

          
 

            GridView1.DataSource = SqlDataSource1;

            GridView1.DataBind();

        

         

    }

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)

    {

        //SqlDataSource1 = new SqlDataSource();

        SqlDataSource1.ConnectionString = new iSession().ConnectionString;
 

        SqlDataSource1.SelectParameters.Clear();

        SqlDataSource1.SelectParameters.Add("lang", DropDownList1.SelectedValue);
 

        GridView1.DataSource = SqlDataSource1;

        GridView1.DataBind();
 

        

        
 

        

    }

Open in new window

0
Comment
Question by:indy28
2 Comments
 
LVL 33

Accepted Solution

by:
raterus earned 500 total points
ID: 21834656
At the top of your .aspx page, in the page directive, is AutoEventWireUp true or false?  If it's true, you need to get rid of these lines, because they'll just double up your events.

        DropDownList1.SelectedIndexChanged += new EventHandler(DropDownList1_SelectedIndexChanged);
        GridView1.RowCommand += new GridViewCommandEventHandler(GridView1_RowCommand);
        GridView1.RowUpdating += new GridViewUpdateEventHandler(GridView1_RowUpdating);
0
 
LVL 11

Expert Comment

by:anuragal
ID: 21840362
try Deleting statements

DropDownList1.SelectedIndexChanged += new EventHandler(DropDownList1_SelectedIndexChanged);

GridView1.RowUpdating += new GridViewUpdateEventHandler(GridView1_RowUpdating);

from the page load function, as you have already mentioned the eventhandlers in .aspx page in <asp:DropDownList & <asp:GridView tags respectively

I hope this will work

Anurag
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

930 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now