Solved

Gridview throws index out of rang error on RowUpdating

Posted on 2008-06-20
2
1,313 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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:Anurag Agarwal
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

Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

Question has a verified solution.

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

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This is a high-level webinar that covers the history of enterprise open source database use. It addresses both the advantages companies see in using open source database technologies, as well as the fears and reservations they might have. In this…
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…

687 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