Mitchel Stuart Fountaine Mitchel Stuart Fountaine - 3 months ago 21
C# Question

IndexOutOfRange Exception when working with DataTable

I'm using StreamReader to access to CSV text file and read all the lines to a DataTable.

public static DataTable ConvertToDataTable(string filePath, int numberOfColumns)
{
DataTable tbl = new DataTable();

for (int col = 0; col < numberOfColumns; col++)
tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString()));

string line;
System.IO.StreamReader file = new StreamReader("C:/ProgramData/3CX/Instance1/Data/Logs/CDRLogs/cdr.log");

while ((line = file.ReadLine()) != null)
{
var cols = line.Split(',');
DataRow dr = tbl.NewRow();
for (int cIndex = 0; cIndex < cols.Length + 1; cIndex++)
{
dr[cIndex] = cols[cIndex];
}
tbl.Rows.Add(dr);
}


Once I've added all the CSV rows to the DataTable I want to iterate through the rows and remomve unwanted rows on conditions.

DataTable dt = ConvertToDataTable("C:/ProgramData/3CX/Instance1/Data/Logs/CDRLogs", 4);

for (int i = 0; i < dt.Rows.Count; i++)
{
string duration = dt.Rows[i][1].ToString();
if (duration == "")
{
dt.Rows[i].Delete();
}
Console.WriteLine(i.ToString() + dt.Rows[i][1].ToString());
}


This runs just fine until I reach the last row, where it seems to be looping through a row that doesn't exist.

Anyone have an idea as to why? Any and all help would be greatly appreciated!

Answer

When you deleting the row, you shouldn't set i=i+1 ,because amount or rows was decreased

        int i = 0; 
        while(i < dt.Rows.Count)
        {
            string duration = dt.Rows[i][1].ToString();
            if (duration == "")
            {
                dt.Rows[i].Delete();
            }
            else
            {i++;}
            Console.WriteLine(i.ToString() + dt.Rows[i][1].ToString());
        }
Comments