What is the solution to the "There Is now at position 7" error? - C# DataTable

Ulas KAYALAR 236 Reputation points
2021-06-02T12:07:49.367+00:00

Hello to everyone,

I'm saving all rows in a specific column in an Excel table to the database. There is no problem, all the data in the column of the table I want is transferred to the database. However, when it comes to the last row, I encounter the error 'there is now at position'. However, when I checked it with the debugger, the data in the row was pulled. So even though the data is being pulled, not null, I'm getting this error. Strangely enough, the data on the row where I got the error is saved to the database without any problems. What is the solution to the problem?

Excel;
101688-excel.png

Database;
101743-database.png

As you can see the last line has been printed to the database. However, I am getting an error.

C#

foreach (DataRow drow in dTable.Rows)  
                {  
                    for (int i = 0; i <= dTable.Rows.Count; i++)  
                    {  
                        object value = dTable.Rows[i][2].ToString();  
                        if (value != DBNull.Value)  
                        {  
                            using (MySqlConnection conn = new MySqlConnection(connStr))  
                            {  
                                conn.Open();  
                                using (MySqlCommand cmd = new MySqlCommand("INSERT INTO aList(sN) VALUES(@sN)", conn))  
                                {  
                                    cmd.Parameters.AddWithValue("@sN", dTable.Rows[i][2].ToString());  
                                    int check = cmd.ExecuteNonQuery();  
                                    conn.Close();  
  
                                }  
                            }  
                        }  
                        else { }                               
                            
                    }  
                }  

DataTable row count;
101667-rowcount.png

Row 7 actually exists and the data in it has been pulled;
101668-value.png

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,405 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,608 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 114.4K Reputation points
    2021-06-02T13:10:39.073+00:00

    Try 'i < dTable.Rows.Count' instead of 'i <= dTable.Rows.Count'.

    Also try 'object value = dTable.Rows[i][2]' without .ToString().


1 additional answer

Sort by: Most helpful
  1. Ulas KAYALAR 236 Reputation points
    2021-06-02T15:33:38.273+00:00

    Here is the solution;

     foreach (DataRow drow in dTable.Rows)
     {
    
       var value = drow[2].ToString();
    
     }
    
    0 comments No comments