6

I have a DataTable which is populated by a csv file, with 8 columns and approximately 2000 rows. I wish to populate an object with my csv values that are currently stored in my DataTable

How do I index a specific DataTable cell? In other words, I wish to treat the data table in a similar way you would a 2D array, like so:

string value = array[i][j];

Here is my code:

DataTable d = GetDataTableFromCSVFile(file);
for (int i = 0; i < d.Rows.Count; i++)
{
    for (int j = 0; j < d.Columns.Count; j++)
    {
         //string x = d[i][j]; <-- something like this.
    }
} 
Barney Chambers
  • 2,720
  • 6
  • 42
  • 78

3 Answers3

12

like this

string x = d.Rows[i][j].ToString()
nan lin
  • 368
  • 2
  • 8
1

The best way to iterate the DataTable. Foreach works faster then for loop:

foreach (DataRow dtRow in dtTable.Rows)
{
    foreach(DataColumn dc in dtTable.Columns)
    {
      var field1 = dtRow[dc].ToString();
    }
}
Koby Douek
  • 16,156
  • 19
  • 74
  • 103
Sanjay
  • 93
  • 1
  • 6
1

You can use for each loop to get your data.

            string x = string.Empty;
            DataTable d = FileHelpers.CommonEngine.CsvToDataTable(@"D:\Sacramentorealestatetransactions.csv", "Sacramentorealestatetransactions", ',', true); // Get FileHelpers package from NuGet
            foreach(DataRow row in d.Rows)
                foreach (object dc in row.ItemArray)
                    x = dc.ToString();
cSharma
  • 636
  • 8
  • 21