Home > Blockchain >  print an entire table in C#
print an entire table in C#

Time:11-09

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

CodePudding user response:

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

CodePudding user response:

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

  • Related