0

I 'm trying to loop through a datatable and print out the values of the

  • 0,
  • 1 and
  • 4th cell of each row,

And it feels like this should be working but I'm probably messing up the loop somehow.

 foreach (DataRow dr in dt.Rows)
 {
      for (int x = 0; x < dt.Rows.Count; x++)
      {
          Console.WriteLine(dt.Columns[0].ColumnName + " ");
          Console.WriteLine(dt.Rows[x].ItemArray[0].ToString() + " ");
          Console.WriteLine(dt.Columns[1].ColumnName + " ");
          Console.WriteLine(dt.Rows[x].ItemArray[1].ToString() + " ");
          Console.WriteLine(dt.Columns[4].ColumnName + " ");
          Console.WriteLine(dt.Rows[x].ItemArray[4].ToString() + " ");
       }
 }

The above code gives me this error:

The system cannot execute the specified program.

2
  • 2
    Well for starters you only need either the foreach or the for loop. You don't need both.
    – Deolus
    Aug 28, 2020 at 5:42
  • 1
    If you want just values, you probably can just go foreach (var dr in dt.Rows) Console.WriteLine($"{dr[0]} - {dr[1]} - {dr[4]}");
    – timur
    Aug 28, 2020 at 6:36

3 Answers 3

2

Remove one of the loops:

                for (int x = 0; x < dt.Rows.Count; x++)
                {
                    Console.WriteLine(dt.Columns[0].ColumnName + " ");
                    Console.WriteLine(dt.Rows[x].ItemArray[0].ToString() + " ");
                    Console.WriteLine(dt.Columns[1].ColumnName + " ");
                    Console.WriteLine(dt.Rows[x].ItemArray[1].ToString() + " ");
                    Console.WriteLine(dt.Columns[4].ColumnName + " ");
                    Console.WriteLine(dt.Rows[x].ItemArray[4].ToString() + " ");
                }

Or

                foreach (DataRow dr in dt.Rows){
                    Console.WriteLine($"{dr[0]} - {dr[1]} - {dr[4]}");
                }
1
  • thanks! dont know why i thought i needed two loops to get all the values
    – chessmt
    Aug 29, 2020 at 0:37
1

You don't need to surround your for loop with a foreach loop on the Rows. (You are not using the dr at all)

for (int idx = 0; idx < dt.Rows.Count; idx++)
{
    Console.WriteLine(dt.Columns[0].ColumnName + " ");
    Console.WriteLine(dt.Rows[idx].ItemArray[0] + " ");
    Console.WriteLine(dt.Columns[1].ColumnName + " ");
    Console.WriteLine(dt.Rows[idx].ItemArray[1] + " ");
    Console.WriteLine(dt.Columns[4].ColumnName + " ");
    Console.WriteLine(dt.Rows[idx].ItemArray[4] + " ");
}

A bit more generic version:

int[] columnIndexes = new[] { 0, 1, 4 };
for (int rowIndex = 0; rowIndex < dt.Rows.Count; rowIndex++)
{
    for (int columnIndex = 0; columnIndex < columnIndexes.Length; columnIndex++)
    {
        Console.WriteLine(dt.Columns[columnIndex].ColumnName + " ");
        Console.WriteLine(dt.Rows[rowIndex].ItemArray[columnIndex] + " ");
    }
}

If you want to iterate through the Rows collection with foreach then you can do but it is a bit more trickier.

DataTable's Rows property is a DataRowCollection. It exposes a GetEnumerator method, which is essential for the foreach loop.

foreach (DataRow dr in dt.Rows)
{
    //dr does not provide you direct access to the ColumnName
}

You can't access the ColumnName from the DataRow directly. All need to do is to create a "lookup table" for the column names where the key is the index and the value is the name of the column.

int colIdx = 0;
var columnNames = dt.Columns
    .Cast<DataColumn>()
    .ToDictionary(_ => colIdx++, column => column.ColumnName);

After that your foreach loop would look like this:

int[] columnIndexes = new[] {0, 1, 4};
foreach (DataRow row in dt.Rows)
{
    for (int columnIndex = 0; columnIndex < columnIndexes.Length; columnIndex++)
    {
        Console.WriteLine(columnNames[columnIndex] + " ");
        Console.WriteLine(row.ItemArray[columnIndex] + " ");
    }
}
3
  • now rather than writing the line if i wanted to store the value of the item array in a string ex: string toEmail = dt.Rows[idx].ItemArray[4].ToString(); console.writeline(toEmail); once again throws that same error i encountered. because the endgame im going for is looping through this table using those 3 values to populate multiple strings that will be the to/from/body of an email
    – chessmt
    Aug 29, 2020 at 1:45
  • 1
    @chessmt In order to be able to help you with the error I need to see the modified code and the whole stacktrace of the exception. Please do not modify the original question's code rather open a new question and link here please. Aug 29, 2020 at 9:16
  • 1
    I am pretty sure that you can access DataRow.Items by their names
    – timur
    Aug 29, 2020 at 22:44
0

I just wanted to point out that you indeed can access values in a DataRow by column name. That functionality is available in full .net framework as well as .net core (so you are covered regardless of which one you use). This of course carries a slight performance hit because it seems to end up doing a Dictionary lookup.

One advantage you get from taking this route is you'd be less dependant on table structure changes in future - which might be a tradeoff worth considering.

Then your intention could be expressed like so:

foreach (DataRow row in dt.Rows)
    Console.WriteLine($"{row["Col0"]} - {row["Col1"]} - {row["Col4"]}");

now, suppose you want to drop foreach and and go LINQ:

void Main()
{
    var dt = new DataTable();
    dt.Columns.Add("Col0", typeof(string));
    dt.Columns.Add("Col1", typeof(string));
    dt.Columns.Add("Col2", typeof(string));
    dt.Columns.Add("Col3", typeof(string));
    dt.Columns.Add("Col4", typeof(string));
    
    dt.Rows.Add("one","two","three","four","five");
    dt.Rows.Add("ten","eleven","twelve","thirteen","fourteen");

    var formattedItems = dt.Rows // declaring a lise you'd open yourself up to further processing the results rather than just pringint them
                            .Cast<DataRow>() // DataRow collection does implement IEnumerable through its base InternalDataCollectionBase class but we seem to need this cast in order to properly expose it
                            .Select(row => $"{row["Col0"]} - {row["Col1"]} - {row["Col4"]}") // and now we can unleash the LINQ
                            .ToList(); // depending on your further processing code you can either enumerate it now or have it sitting around until you actually need to loop through it
    
    Console.WriteLine(formattedItems.Aggregate(new StringBuilder(), (sb, s) => sb.AppendLine(s)).ToString()); // just slapping list items together in a string to print out for your convenience
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.