1

我正在创建Dynamic HTML Table填充了使用数据的DataTable标记C#。我正在使用StringBuilder对象 Built-up HTML 标记。编译时出现错误“无法将字符串转换为字符串生成器

代码:

DataTable dt=new DataTable();
dt=GetData();
StringBuilder strDeviceList=new StringBuilder();
strDeviceList = "<table style='width:100%;text-align:center;'>" +
                            "<tr>" +
                                "<td> Quote ID</td><td>Device</td><td> Generation</td><td>Condition</td><td>Price</td>" +
                            "</tr>";                          
            foreach (DataRow row in dt.Rows)
            {
                strDeviceList.Append("<tr>" +
                 "<td>" + row["QuoteID"] + "</td><td>" + row["Name"] + "</td><td>" + row["Generation"] + "</td><td>" + row["Condition"] + "</td><td>" + row["Price"] + "</td>" +
                 "</tr>");
            }
strDeviceList.Append("</table>");

任何想法?帮助赞赏!

4

2 回答 2

3

更改此行,在您尝试分配的代码中stringStringBuilder这是编译错误的原因

strDeviceList.Append("<table style='width:100%;text-align:center;'>" +
                            "<tr>" +
                                "<td> Quote ID</td><td>Device</td><td> Generation</td><td>Condition</td><td>Price</td>" +
                            "</tr>"); 

或更清洁

strDeviceList.Append("<table style='width:100%;text-align:center;'>");
strDeviceList.Append("<tr>");
strDeviceList.Append("<td> Quote ID</td><td>Device</td><td> Generation</td><td>Condition</td><td>Price</td>");
strDeviceList.Append("</tr>"); 

您可以使用AppendFormat字符串附加动态值

foreach (DataRow row in dt.Rows)
{
    strDeviceList.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td></tr>",row["QuoteID"],row["Name"],row["Generation"],row["Condition"],row["Price"]);
}
于 2013-11-14T07:25:40.657 回答
0
strDeviceList = "...."; //wrong

strDeviceList.AppendLine("...."); //use this
strDeviceList.AppendFormat("<td>{0}</td>", row["Name"]); //even smarter

还有一件事是 StringBuilder .Append 比字符串连接运算符具有更好的性能

//instead of native string concat
string str = "aaa" + "bbb" + "ccc";

//builder is faster when performing multiple string concat
StringBuilder builder = new StringBuilder();
builder.Append("aaa");
builder.Append("bbb");
builder.Append("ccc");
string str = builder.ToString();
于 2013-11-14T07:37:46.533 回答