Click here to Skip to main content
15,901,373 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
hi! when I run Below code it shows an error like "An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll
Additional information: Cannot find column 2."

Can anyone help me to find the solution ?

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
using Excel;
using System.Data.Sql;

namespace ProjectTrackingExcel
{
public partial class Form2 : Form
    { 
 private void button3_Click(object sender, EventArgs e)
        {
            OpenFileDialog op = new OpenFileDialog();
            op.Filter = "Excel filters|*.xls;*.xlsx;*.xlxm|Excel2003*xlsx)|*.xlsx";
            if (op.ShowDialog() == DialogResult.Cancel)
                return;

            FileStream strm = File.Open(op.FileName,FileMode.Open,FileAccess.Read); 
            IExcelDataReader exceldata ExcelReaderFactory.CreateBinaryReader(strm);

            DataSet result = exceldata.AsDataSet();

            DataClasses1DataContext con = new DataClasses1DataContext();

            foreach (DataTable table in result.Tables) {

                foreach (DataRow dr in table.Rows){
                   
                  Proj addTable = new Proj (){
                  
                   id = Convert.ToString(dr[0]),
                   name = Convert.ToString(dr[1]),
                   city = Convert.ToString(dr[2]),
                   gender = Convert.ToString(dr[3])
                  
                  };

                  con.Projs.InsertOnSubmit(addTable)  
                }
                 }
                    con.SubmitChanges();
                    exceldata.Close();
                    strm.Close();

            MessageBox.Show("Data Successfully added to the database");

            }    
        }
}


What I have tried:

I referred some solutions of your site as well. But still, occurs the same problem.
Posted
Updated 19-Jul-16 22:20pm
v2

"Index out of range" means just that: you are trying to access an array element by using an index value that is larger than the maximum index value.
If you declare an array of of integers:
C#
int[] ints = new int[3];

Then you can access it happily using the index:
C#
int a = ints[0];
int b = ints[1];
int c = ints[2];
But if you try to use a negative number, or a value greater than two you will get the error "Index out of range" because there is no element at that index value.

Your code uses "magic numbers" - which is generally a bad idea - and it's almost certainly this line that causes the problem:
C#
city = Convert.ToString(dr[2]),
Since the addition info says it's "column 2" it can't find.
I'd start by using the debugger to find out what is in the DataReader: put a breakpoint on the line
C#
Proj addTable = new Proj ()
And run your app in the debugger.
When it hits that line, it will stop, and let you look at exactly what is in the variables.
Look to your data: it's probably something to do with the problem - and you need the actual data it read to identify exactly what is going on.

Sorry, but we can't do any of that for you: we don't have your data files, so we can't duplicate your problem here!
 
Share this answer
 
Your problem seems to be in following piece of code-
C#
Proj addTable = new Proj (){

id = Convert.ToString(dr[0]),
name = Convert.ToString(dr[1]),
city = Convert.ToString(dr[2]),
gender = Convert.ToString(dr[3])

};


Before trying to access a column of data row check if that datarow really exists.
You can check with something like-
C#
int noOfCols = dr.Table.Columns.Count;


For a workaround, you can do like-
C#
Proj addTable = new Proj (){

id = dr.Table.Columns.Count>0 ? Convert.ToString(dr[0]) : String.Empty,
name = dr.Table.Columns.Count>1 ? Convert.ToString(dr[1]) : String.Empty,
city = dr.Table.Columns.Count>2 ? Convert.ToString(dr[2]) : String.Empty,
gender = dr.Table.Columns.Count>3 ? Convert.ToString(dr[3]) : String.Empty

};


Note: I haven't tested this code and may contain syntax errors.

Hope, it helps :)
 
Share this answer
 
Comments
Karthik_Mahalingam 20-Jul-16 4:21am    
5! for workaround
Suvendu Shekhar Giri 20-Jul-16 4:31am    
Thanks :)

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