Index out of range

  • 13 years ago

    hi all,

    When I delete a record from the gridview it gives me the following error:

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

    Line 116:        int rowno= Convert.ToInt32(e.RowIndex);
    Line 117:        string delval = GridView1.Rows[rowno].Cells[1].Text;
    Line 118:         string strstate = "delete from tb_citystate_master where citystate_nm= '" + delval + "'";
     

    But when I check with the database the record is deleted.

    The flow of module is like this:

    - When the form loads, the gridview is binded with the data from the database. 

    - The gridview has a button "Delete" for deleting a row.

    - When the record is deleted the gridview is re-binded with the data from database(after deleting the current record).(I think the problem is somewhere here).

     What should I do to slove this?

    My databinding code is:

    public void showstate()

    {

    string st = "Data Source=newgeneration;Initial Catalog=testcheema;Integrated Security=True";SqlConnection con = new SqlConnection(st);

    con.Open();

    string strstate = "select citystate_cd, citystate_nm from tb_citystate_master where statelink_cd=0";

    SqlDataAdapter adp = new SqlDataAdapter(strstate, con);DataSet ds = new DataSet();

    adp.Fill(ds);

    GridView1.DataSource = ds;

    GridView1.DataBind();

    con.Close();

    }

     

    Regards,

    Royal

  • 13 years ago

    [quote](I think the problem is somewhere here).[/quote]

    Royal, have you stepped through your code to see where the exception is thrown? ... you should be able to trace to exactly where it occurs. If it helps, paste up the full exception message generated - the one that shows the stack trace.

    Joe 

  • 13 years ago

    hi Joe,

    The stack trace looks something like:

    [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) +2776157
       System.Web.UI.WebControls.GridViewRowCollection.get_Item(Int32 index) +10
       finalformlayout_state_master.GridView1_RowDeleting(Object sender, GridViewDeleteEventArgs e) in e:\Desktop Items\Cheema\WebSites\payrolldemo\finalformlayout\state_master.aspx.cs:117
       System.Web.UI.WebControls.GridView.OnRowDeleting(GridViewDeleteEventArgs e) +99
       System.Web.UI.WebControls.GridView.HandleDelete(GridViewRow row, Int32 rowIndex) +610
       System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +1152
       System.Web.UI.WebControls.GridView.RaisePostBackEvent(String eventArgument) +190
       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) +170
       System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4921

    While doing the de-bugging(when i deleted a record) I was in a Jargon seeing the way it was jumping from one function to another(in some cases). Specially between 2 functions: 1 for getting new state code the other for binding gridview with state names.

    Can you find out something from the stack trace?

    Regards,

    Royal

  • 13 years ago

     Royal, the stack trace can sometimes be useful to show what events were firing when the exception occurred. I thought, given your stack trace that it may have had something to do with "OnRowDeleting"... so I have tried to replicate your problem using a little intuition and as much of your code as you supplied. Code as follows:

    html:

    <body>
        <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDeleting="GridView1_RowDeleting">
                <Columns>
                    <asp:BoundField DataField="citystate_cd" HeaderText="city state cd" />
                    <asp:BoundField DataField="citystate_nm" HeaderText="city state nm" />
                    <asp:CommandField ShowDeleteButton="True" />
                </Columns>
            </asp:GridView>
       
        </div>
        </form>
    </body>


    c#:

            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    this.showstate();
                }
            }

            public void showstate()
            {
                string st = @"Data Source=sqlexpress;Initial Catalog=testbed;Integrated Security=True";
                SqlConnection con = new SqlConnection(st);
                con.Open();

                string strstate = "select citystate_cd, citystate_nm from tb_citystate_master where statelink_cd=0";
                SqlDataAdapter adp = new SqlDataAdapter(strstate, con);
                DataSet ds = new DataSet();

                adp.Fill(ds);

                GridView1.DataSource = ds;

                GridView1.DataBind();

                con.Close();

            }

            protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
            {
                string st = @"Data Source=sqlexpress;Initial Catalog=testbed;Integrated Security=True";
                SqlConnection con = new SqlConnection(st);
                con.Open();

                int rowno= Convert.ToInt32(e.RowIndex);
                string delval = GridView1.Rows[rowno].Cells[1].Text;
                string strstate = "delete from tb_citystate_master where citystate_nm= '" + delval + "'";

                SqlCommand cmd = con.CreateCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = strstate;
                cmd.ExecuteNonQuery();

                //refresh
                this.showstate();
            }
        }

     But the result is that it all works a-ok... so I figure that you must be doing some other processing that you didn't mention. Have a look at the above and see where the differences are to your own code. Perhaps there is something obvious that you can then see. For instance, are you doing some more processing in the data-bound event - ie when each row is loaded into the grid?

    Joe
     

Post a reply

Enter your message below

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“We better hurry up and start coding, there are going to be a lot of bugs to fix.”