c# - 我的类库类中的 StringBuilder html 表

标签 c# asp.net stringbuilder

我的类库中有一个类,它有一个方法,该方法使用带有 SqlDataReader 的列表来循环遍历所有记录。

public List<myDetails> GetAddressDetails(int id)
{
    List<myDetails> mydetails = new List<myDetails>();
    myDetails details;

    try
    {
        using (SqlDataReader rdr = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                details = new myDetails((
                    reader.GetString(reader.GetOrdinal("FieldName")));

                mydetails.Add(details);
        }
        rdr.Close();
        return mydetails;
    }
}

我正在尝试使用 StringBuilder 构建 HTML 表,但无法弄清楚如何正确循环我的列表集合。我尝试了几个不同的 for 循环,但它们没有给出正确的结果。

    var item = clib.GetAddressDetails(Convert.ToInt32(Session["mysession"]));

        if (item != null)
        {      
            StringBuilder htmlStr = new StringBuilder("");
            htmlStr.Append("<center><h2 class='headings'>Addresses</h2>");
            htmlStr.Append("<table border='1' cellpadding='3'>");

foreach (var detail in item)
{
            htmlStr.Append("<tr>");
            htmlStr.Append("<td width='25px'>" + item.FieldName + "</td><tr>");
            htmlStr.Append("</tr>");
            htmlStr.Append("</table></center><br/>");
            divAddresses.InnerHtml = htmlStr.ToString();   
    }


        }

最佳答案

您需要使用循环。 foreach 或简单的 forwhile 循环都可以:

// initialize the string builder outside the loop!
StringBuilder htmlStr = new StringBuilder("");

// build out the header outside the loop..
htmlStr.Append("<center><h2 class='headings'>Addresses</h2>");
htmlStr.Append("<table border='1' cellpadding='3'>");

// retrieve the id from the session
int id = Convert.ToInt32(Session["mysession"]);

// then loop over the items returned
foreach(var item in clib.GetAddressDetails(id))
{
    if (item != null)
    {                                       
        htmlStr.Append("<tr>");
        htmlStr.Append("<td width='25px'>" + item.FieldName + "</td><tr>");
        htmlStr.Append("</tr>");
    }
}

// finish building your table outside the loop..
htmlStr.Append("</table></center><br/>");

// set the contents of the string builder as the inner HTML of the DIV element
divAddresses.InnerHtml = htmlStr.ToString(); 

关于c# - 我的类库类中的 StringBuilder html 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19278929/

相关文章:

asp.net - 通过 OWIN 中间件路由所有请求

ASP.NET - 中等信任度的 PDF 组件

java - Java 中的 StringBuilder 初始化

c# - C# WPF 中奇怪的换行行为

C#:检索非参数化存储过程查询的输出参数?

javascript - 如何在 asp.net 中显示下拉列表的所有项目?

c# - 关于 C# 中 RCON 协议(protocol)实现的令人难以置信的问题

java - 是否是 StringBuilder 错误?

c# - 如何在 ADO.NET EF 4.1 中插入记录?

c# - 无法在 javascript 中获取 html 文本框的值