Search code examples
c#datatablehtml-agility-pack

Why do I get System.Data.DataRow? instead of datatable (I've retrieved a table from outlook as html body then I've parse it to a data table)


I've retrieved a table from outlook as html body then I've parse it to a datatable but when I run the code, all I get is System.Data.DataRow

static void Main(string[] args)
{
        var mails = OutlookEmails.ReadMailItems();

        foreach (var mail in mails)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(mail.EmailBody.ToString());

            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(builder.ToString());

            var nodes = doc.DocumentNode.SelectNodes("//table//tr");
            DataTable dataTable = new DataTable();

            var headers = nodes[0]
                .Elements("th")
                .Select(th => th.InnerText.Trim());

            foreach (var header in headers)
            {
                dataTable.Columns.Add(header);
            }

            var rows = nodes.Skip(1).Select(tr => tr
                .Elements("td")
                .Select(td => td.InnerText.Trim())
                .ToArray());

            foreach (var row in rows)
            {
                dataTable.Rows.Add(row);
            }
        
            Console.WriteLine(dataTable.Rows);
            Console.ReadLine();
        }
    }

Solution

  • Because you are just printing out the type of the object. If you want to print out every column for every row in your dataTable, you must specify that:

    foreach (DataRow row in dataTable.Rows) 
    {
        Console.WriteLine();
        foreach (DataColumn col in dataTable.Columns) 
        {
            Console.Write(row[col] + " ");
        }
    }
    

    For further information: MS DataTable Docs