gymcode
gymcode

Reputation: 4623

C# HTML table not in correct output format

I am forming a HTML table to a string format to be parsed back to another function to be displayed in an email.

However, I feel like I am missing out on a lot of things as I am unable to get the table to be in the correct output.

Below is my code snippet:

var table = new HtmlTable();
var mailMessage = new StringBuilder();
string html;

HtmlTableRow row;
HtmlTableCell cell;

row = new HtmlTableRow();

row.Cells.Add(new HtmlTableCell { InnerText = "First Name" });
row.Cells.Add(new HtmlTableCell { InnerText = "Last Name" });
row.Cells.Add(new HtmlTableCell { InnerText = "Age" });

table.Rows.Add(row); //seems to not adding a new row at this statement

row.Cells.Add(new HtmlTableCell { InnerText = "Jane" });
row.Cells.Add(new HtmlTableCell { InnerText = "Doe" });
row.Cells.Add(new HtmlTableCell { InnerText = "29" });

using (var sw = new StringWriter()){
    table.RenderControl(new HtmlTextWriter(sw));
    html = sw.ToString();
}

mailMessage.AppendFormat(html);
Console.WriteLine(mailMessage.ToString());

Output:

<table>
        <tr>
                <td>First Name</td>
                <td>Last Name</td>
                <td>Age</td>
                <td>Jane</td>
                <td>Doe</td>
                <td>29</td>
        </tr>
</table>

Upvotes: 0

Views: 194

Answers (1)

Codeek
Codeek

Reputation: 1624

Try this after your code :

table.Rows.Add(row);

row = new HtmlTableRow();

and after setting data td, add the second row to table again using

table.Rows.Add(row);

you need to re-initialize your row variable after adding it.

So your code now will look like as below :

row = new HtmlTableRow();

row.Cells.Add(new HtmlTableCell { InnerText = "First Name" });
row.Cells.Add(new HtmlTableCell { InnerText = "Last Name" });
row.Cells.Add(new HtmlTableCell { InnerText = "Age" });

table.Rows.Add(row); //Add First Row.
row = new HtmlTableRow(); // Reinitialize Row

row.Cells.Add(new HtmlTableCell { InnerText = "Jane" });
row.Cells.Add(new HtmlTableCell { InnerText = "Doe" });
row.Cells.Add(new HtmlTableCell { InnerText = "29" });

table.Rows.Add(row); // Add Second Row

Or better use another variable for sake of removing ambiguity. Like headerRow, firstRow or so.

Upvotes: 1

Related Questions