我的类库中有一个类,它有一个方法,该方法使用带有 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
或简单的 for
或 while
循环都可以:
// 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/