4

I'm trying to print the content of a DataTable, starting with the column headers, followed by the content of the table tupples.

output.Add($"Table : [{dataTable.TableName}]");
string strColumnNames = "";
foreach (DataColumn col in dataTable.Columns)
{
    if (strColumnNames == "")
         strColumnNames = col.ColumnName.PadLeft(col.MaxLength - col.ColumnName.Length);  // (*)
    else strColumnNames = strColumnNames + "|" + 
                          col.ColumnName.PadLeft(col.MaxLength - col.ColumnName.Length);  // (*)
}
output.Add($"[{strColumnNames}]");


foreach (DataRow dataRow in dataTable.Rows)
{
    string temp = "";
    for (int i = 0; i < dataRow.ItemArray.Count(); i++)
    {
        if (i == 0)
            temp = dataRow.ItemArray[i].ToString();                          // (**)
        else temp += "|" + dataRow.ItemArray[i].ToString();                  // (**)
    }
    output.Add($"[{temp}]");
}

The (*) parts in this code are using the MaxLength property of the DataColumns maximum length in order to get a column-like output.

I would like to do the same in the (**) parts, but I don't know how to access the corresponding DataColumn, starting from the dataRow object.

Does anybody have an idea?
Thanks in advance

2
  • No need to start from dataRow if you use dataTable... dataTable.Columns[i].MaxLength Commented Nov 8, 2021 at 12:58
  • What is output ? Won't you simplify the process by converting the DataTable to a CSV string before outputing it ? Commented Nov 8, 2021 at 17:17

2 Answers 2

4

You already have the dataTable instance available. dataTable.Columns[i] should give you the appropriate DataColumn.

Sign up to request clarification or add additional context in comments.

Comments

1

Datatable has already been instantiated here. If you want to print the datacolumn you should use dataTable.Column[i] for the appropriate column.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.