简体   繁体   中英

print an entire table in C#

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 DataColumn s 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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM