Dynamically create HTML table in C#

前端 未结 4 1522
逝去的感伤
逝去的感伤 2020-12-30 06:40

Is there more efficient way to build HTML table than the one I\'m trying on right now?

I\'m getting an object and it has some list of entities in it. So I need to pa

4条回答
  •  一生所求
    2020-12-30 07:17

    As I've recently come to play with creating IDisposable classes, I think this would be both efficient for this specific task, and much easier to read:

    Create some very simple classes

        /// 
        /// https://stackoverflow.com/a/36476600/2343
        /// 
        public class Table : IDisposable
        {
            private StringBuilder _sb;
    
            public Table(StringBuilder sb, string id = "default", string classValue="")
            {
                _sb = sb;
                _sb.Append($"\n");
            }
    
            public void Dispose()
            {
                _sb.Append("
    "); } public Row AddRow() { return new Row(_sb); } public Row AddHeaderRow() { return new Row(_sb, true); } public void StartTableBody() { _sb.Append(""); } public void EndTableBody() { _sb.Append(""); } } public class Row : IDisposable { private StringBuilder _sb; private bool _isHeader; public Row(StringBuilder sb, bool isHeader = false) { _sb = sb; _isHeader = isHeader; if (_isHeader) { _sb.Append("\n"); } _sb.Append("\t\n"); } public void Dispose() { _sb.Append("\t\n"); if (_isHeader) { _sb.Append("\n"); } } public void AddCell(string innerText) { _sb.Append("\t\t\n"); _sb.Append("\t\t\t"+innerText); _sb.Append("\t\t\n"); } } }

    Then you can define your table using:

    StringBuilder sb = new StringBuilder();
    
    using (Html.Table table = new Html.Table(sb))
    {
        foreach (var invalidCompany in mailMessageObject.InvalidCompanies)
        {
            using (Html.Row row = table.AddRow())
            {
                row.AddCell(invalidCompany.BusinessName);
                row.AddCell(invalidCompany.SwiftBIC);
                row.AddCell(invalidCompany.IBAN);
            }
        }
    }
    
    string finishedTable = sb.ToString();
    

提交回复
热议问题