Bestcomy.net blog

Coding for funny

导航

Two ways to get HtmlTextWriter for HTML rendering

Posted on 2006-11-02 16:03  bestcomy  阅读(1383)  评论(0编辑  收藏  举报

I need to render some html in my asp.net applications sometime, I chose HtmlTextWriter to build the html source because I can use those handy methods of this object such as RenderBeginTag, AddAttribute, and so on. I know two ways to do this.

 1 StringBuilder sb = new StringBuilder();
 2             using(StringWriter sw = new StringWriter(sb))
 3             {
 4                 using(HtmlTextWriter output = new HtmlTextWriter(sw))
 5                 {
 6                     output.RenderBeginTag(HtmlTextWriterTag.Table);
 7                     for(int y=0; y<1000; y++)
 8                     {
 9                         output.RenderBeginTag(HtmlTextWriterTag.Tr);
10                         for(int x=0; x<100; x++)
11                         {
12                             output.RenderBeginTag(HtmlTextWriterTag.Td);
13                             output.Write("&nbsp;");
14                             output.RenderEndTag();
15                         }
16                         output.RenderEndTag();
17                         output.Flush();
18                     }
19                     output.RenderEndTag();
20                     Response.Write(output.ToString());
21                 }
22             }

 1 using(MemoryStream stream = new MemoryStream())
 2             {
 3                 using(TextWriter tw = new StreamWriter(stream,System.Text.Encoding.UTF8) as TextWriter)
 4                 {
 5                     using(HtmlTextWriter output = new HtmlTextWriter(tw))
 6                     {
 7                         output.RenderBeginTag(HtmlTextWriterTag.Table);
 8                         for(int y=0; y<1000; y++)
 9                         {
10                             output.RenderBeginTag(HtmlTextWriterTag.Tr);
11                             for(int x=0; x<100; x++)
12                             {
13                                 output.RenderBeginTag(HtmlTextWriterTag.Td);
14                                 output.Write("&nbsp;");
15                                 output.RenderEndTag();
16                             }
17                             output.RenderEndTag();
18                         }
19                         output.RenderEndTag();
20                         output.Flush();
21                         Response.Write(output.ToString());
22                     }
23                 }
24             }