Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IndexOutOfRange Exception when working with DataTable

Tags:

c#

.net

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!

like image 352
Mitchel Stuart Fountaine Avatar asked Feb 16 '26 14:02

Mitchel Stuart Fountaine


1 Answers

You can iterate trough the rows backwards to keep the indices as they are.

for(int i = dt.Rows.Count - 1; i >= 0; i--)
{
   dt.Rows[i].Delete();
}
like image 111
Allmighty Avatar answered Feb 19 '26 04:02

Allmighty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!