Monday, March 26, 2012

stringbuilder question

i am calling the function "ClientInfo" from a repeater. i.e.


<itemtemplate>
<%# ClientInfo(((IDataRecord)Container.DataItem)["CLIENTCODE"].ToString())%>
</itemtemplate>

i am using stringbuilder within my function for the first time. it is working but i just wanted to make sure i am using the stringbuilder correctly. in particular, are my last 2 lines ok i.e. do i have to convert the stringbuilder back to a string in order to return the final HTML output? thanks


public string ClientInfo(string clientCode)
if (clientCode == previousclientCode)
{
System.Text.StringBuilder clientInfoStr = new System.Text.StringBuilder();
clientInfoStr.Append("<table width='100%' border='0'>");
clientInfoStr.Append("<tr class='searchresrow1'>" + SRreader.GetString(3) + "</td>");
string clientInfo = clientInfoStr.ToString();
return clientInfo;
}
else ...
In your case StringBuilder is useless, because you don't concatinate much.
I suggest you to use string.format instead of stringbuilder

For example:
<code>
string ClientInfoStr = @."
<table width='100%' border='0'>
<tr class='searchresrow1'>{0}</td>";
return string.Format(ClientInfoStr, SRreader.GetString(3));

Much simpler and faster.
HTH
sorry - i am in fact returning a long string but i cut it down to 2 lines on my post so people wouldnt get put off!

string clientInfo = clientInfoStr.ToString();

return clientInfo;

could just as well be:


return clientInfoStr.ToString();

This would save the extra String var declaration on clientInfo.

JD

0 comments:

Post a Comment