Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Index was out of range. Must be non-negative and less than the size of the collection. i am try to update the data in grid view. The above error encountered.


C#
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int userid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
        GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
        Label lblID = (Label)row.FindControl("lblID");
          
        TextBox textName = (TextBox)row.Cells[0].Controls[0];
        TextBox textadd = (TextBox)row.Cells[1].Controls[0];
        TextBox textc = (TextBox)row.Cells[2].Controls[0];

        GridView1.EditIndex = -1;
        GridView1.DataBind();
        conn.Open();

        SqlCommand cmd = new SqlCommand("update detail set name='" + textName.Text + "',address='" + textadd.Text + "',country='" + textc.Text + "'where userid='" + userid + "'", conn);
        cmd.ExecuteNonQuery();
        conn.Close();
        gvbind();
    }


What I have tried:

I try to update the record in gridview.
Posted
Updated 29-Jan-18 19:43pm
Comments
F-ES Sitecore 30-Jan-18 4:08am    
It's probably one of your "Cells[?]" lines and there aren't enough cells in the row so your assumption is failing. We can't tell you if the data in the row is wrong or if your assumption that there are at least 3 cells is wrong, and that will drive the exact solution.
F-ES Sitecore 30-Jan-18 4:08am    
It's probably one of your "Cells[?]" lines and there aren't enough cells in the row so your assumption is failing. We can't tell you if the data in the row is wrong or if your assumption that there are at least 3 cells is wrong, and that will drive the exact solution.

Quote:
Index was out of range. Must be non-negative and less than the size of the collection.

The error occurs when you try to access an index of a collection which is not available. Just validate the index before accessing the item in collection.
example:
List<string> lst = new List<string>(); // Collecion of strings, with 3 Items
       lst.Add("one");
       lst.Add("two");
       lst.Add("three");

       // Note : Most of the C# collections are Zero based Index
       string value = lst[4]; // Index error will be thrown since Index(4) is not availble in the collection.

       // To overcome this error, Validate the Index
       if (lst.Count > 4)  // Index validated
           value = lst[4];  // Now its safe to access the index


I hope you are getting error in the below code block
TextBox textName = (TextBox)row.Cells[0].Controls[0];
        TextBox textadd = (TextBox)row.Cells[1].Controls[0];
        TextBox textc = (TextBox)row.Cells[2].Controls[0];

Instead of finding the control based on the control index, you shall use row.FindControl to find the target element as,
TextBox textName =  (TextBox)row.FindControl("YourTextBoxName");

refer these
Find Control inside gridview [^]

Warning:
Concatenating the sql Query string is vulnerable to SQL Injection[^] attacks
always use Parameterized queries to prevent SQL Injection Attacks in SQL Server[^]
SqlCommand cmd = new SqlCommand("update detail set name='" + textName.Text + "',address='" + textadd.Text + "',country='" + textc.Text + "'where userid='" + userid + "'", conn);

change the above code to
SqlCommand cmd = new SqlCommand("update detail set name=@name,address=@address,country=@country where userid=@userid", conn);
      cmd.Parameters.AddWithValue("@name", name);
      cmd.Parameters.AddWithValue("@address", address);
      cmd.Parameters.AddWithValue("@country", country);
      cmd.Parameters.AddWithValue("@userid", userid);
 
Share this answer
 
v2
Quote:
Index was out of range. Must be non-negative and less than the size of the collection.

Use the debugger and put a breakpoint at beginning to run it step by step and inspect variables and collections size. somewhere you try to access a collection element that doesn't exist.

There is a tool that allow you to see what your code is doing, its name is debugger. It is also a great learning tool because it show you reality and you can see which expectation match reality.
When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]
Debugging C# Code in Visual Studio - YouTube[^]
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
-----
C#
SqlCommand cmd = new SqlCommand("update detail set name='" + textName.Text + "',address='" + textadd.Text + "',country='" + textc.Text + "'where userid='" + userid + "'", conn);

Not a solution to your question, but another problem you have.
Never build an SQL query by concatenating strings. Sooner or later, you will do it with user inputs, and this opens door to a vulnerability named "SQL injection", it is dangerous for your database and error prone.
A single quote in a name and your program crash. If a user input a name like "Brian O'Conner" can crash your app, it is an SQL injection vulnerability, and the crash is the least of the problems, a malicious user input and it is promoted to SQL commands with all credentials.
SQL injection - Wikipedia[^]
SQL Injection[^]
SQL Injection Attacks by Example[^]
PHP: SQL Injection - Manual[^]
SQL Injection Prevention Cheat Sheet - OWASP[^]
 
Share this answer
 
Comments
Member 13650918 30-Jan-18 1:43am    
Thank you for quick respose

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900