1

I am creating Dynamic HTML Table Markup filled with the Data from DataTable using C#. I am using the StringBuilder object Built-up HTML markup. On compilation i am getting error "Unable to Convert string to String builder"

Code:

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>");

Any idea? Help Appreciated!

2 Answers 2

3

Change this line, in your code you are trying to assign string to StringBuilder, that is reason of compilation error

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>"); 

or more cleaner

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>"); 

and you can use AppendFormat to append dynamic values with string

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"]);
}
Sign up to request clarification or add additional context in comments.

Comments

0
strDeviceList = "...."; //wrong

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

one more thing is that StringBuilder .Append has better performance than string concatenation operator

//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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.