HtmlTextWriter solution being added as a WebControl
I have a solution that works, yet it doesn't meet the QA requirements from the customer. Problem is I can't control the location of the WebControls, they need to be relative to a chart that is above these. How I see it, I need开发者_如何学编程 to "compile" the sb.ToString() into a WebControl, which I'll then be able to Controls.Add().
I need to go from this working solution:
private void SetTextBoxes()
{ TextBox myBox = new TextBox(); System.Web.UI.WebControls.Label myLabel = new System.Web.UI.WebControls.Label();// <table><tr> for (int i = 0; i < _module.Values.Count; i++) { myLabel = new System.Web.UI.WebControls.Label(); myLabel.Text = _module.Values[i].Text.ToString() + ": "; myBox = new TextBox(); myBox.BorderStyle = BorderStyle.None; myBox.ReadOnly = true; myBox.Text = _module.Values[i].Value.ToString("n0"); myBox.Columns = myBox.Text.Length; // <td align="center"> Controls.Add(myLabel); Controls.Add(myBox); // </td> } // </tr></table> }
Key is the Controls.Add()
as it ties into a modular system covering this code and a few other WebControls.
I have a suggestion to what the solution may look like.
private string WriteHtml()
{
StringBuilder sb = new StringBuilder();
using (StringWriter stringWriter = new StringWriter(sb))
{
using (HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter))
{
htmlTextWriter.RenderBeginTag(HtmlTextWriterTag.Table);
htmlTextWriter.RenderBeginTag(HtmlTextWriterTag.Tr);
for (int i = 0; i < _module.Values.Count; i++)
{
htmlTextWriter.RenderBeginTag(HtmlTextWriterTag.Td);
htmlTextWriter.Write(string.Format("{0}: {1:n0}"
, _module.Values[i].Text
, _module.Values[i].Value));
htmlTextWriter.RenderEndTag(); // td
}
htmlTextWriter.RenderEndTag(); // tr
htmlTextWriter.RenderEndTag(); // table
}
}
//Controls.Add(sb.ToString());
return sb.ToString();
}
I solved almost the same task. Here is my results:
1) I created small helper method:
public static void RenderControl(Control control, HtmlTextWriter response)
{
var sWriter = new StringWriter();
var htmlWriter = new HtmlTextWriter(sWriter);
control.RenderControl(htmlWriter);
// Write HTML
response.WriteLine(sWriter);
response.Flush();
}
2) At main code if you want to get rendered Html you are doing somthing like this:
StringBuilder sb = new StringBuilder();
using (StringWriter stringWriter = new StringWriter(sb))
{
using (HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter))
{
Control control= new YourControlWithTextBox();
WebControlHelper.RenderControl(control, htmlTextWriter);
return stringWriter.ToString();
}
}
With this implementation you can leave SetTextBoxes() as is. And you get 2 version of same control. Here is 2 huge benefits: a)code is still readable and described in asp.net terms. b)you can use WebControlHelper.RenderControl everywhere where you need solve simmilar task
精彩评论