有时候在项目中需要根据实际传过来的参数来生成不同个数的控件来摆放在页面上,这时候可以重写页面 Render方法来达到目的。
下面提供一个示例来实现,代码如下:
//生成要重写的html代码
private string createInputItem()
{
if (Session["Count"] != null)
{
int icount = int.Parse(Session["Count"].ToString());
StringBuilder sbHtml = new StringBuilder();
#region Input Value
for (int i = 1; i <= icount; i++)
{
sbHtml.Append("<tr align=\"left\"> ");
sbHtml.Append("<td style=\"width:150px\" align=\"left\">");
sbHtml.Append("Schacht " + i.ToString() + " SPN F001 ");
sbHtml.Append("</td> ");
sbHtml.Append("<td style=\"width:80px\" align=\"left\">");
sbHtml.Append("<input name=\"txtSPNF001_" + i.ToString() + "\" type=\"text\" style=\"width:80px\" />");
sbHtml.Append("</td> ");
sbHtml.Append("<td style=\"width:30px\" align=\"left\">");
sbHtml.Append("øC");
sbHtml.Append("</td>");
sbHtml.Append("</tr>");
sbHtml.Append("<tr align=\"left\"> ");
sbHtml.Append("<td style=\"width:150px\" align=\"left\">");
sbHtml.Append("Schacht " + i.ToString() + " T001");
sbHtml.Append("</td> ");
sbHtml.Append("<td style=\"width:80px\" align=\"left\">");
sbHtml.Append("<input name=\"txtT001_" + i.ToString() + "\" type=\"text\" style=\"width:80px\" />");
sbHtml.Append("</td> ");
sbHtml.Append("<td style=\"width:30px\" align=\"left\">");
sbHtml.Append("øC");
sbHtml.Append("</td>");
sbHtml.Append("</tr>");
sbHtml.Append("<tr align=\"left\"> ");
sbHtml.Append("<td style=\"width:150px\" align=\"left\">");
sbHtml.Append("Schacht " + i.ToString() + " T007,T009");
sbHtml.Append("</td> ");
sbHtml.Append("<td style=\"width:80px\" align=\"left\">");
sbHtml.Append("<input name=\"txtT007_T009_" + i.ToString() + "\" type=\"text\" style=\"width:80px\" />");
sbHtml.Append("</td> ");
sbHtml.Append("<td style=\"width:30px\" align=\"left\">");
sbHtml.Append("øC");
sbHtml.Append("</td>");
sbHtml.Append("</tr>");
sbHtml.Append("<tr align=\"left\"> ");
sbHtml.Append("<td style=\"width:150px\" align=\"left\">");
sbHtml.Append("Schacht " + i.ToString() + " VM");
sbHtml.Append("</td> ");
sbHtml.Append("<td style=\"width:80px\" align=\"left\">");
sbHtml.Append("<input name=\"txtVM_" + i.ToString() + "\" type=\"text\" style=\"width:80px\" />");
sbHtml.Append("</td> ");
sbHtml.Append("<td style=\"width:30px\" align=\"left\">");
sbHtml.Append("øC");
sbHtml.Append("</td>");
sbHtml.Append("</tr>");
}
#endregion
return sbHtml.ToString();
}
return string.Empty;
}
protected override void Render(HtmlTextWriter writer)
{
StringWriter sw = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
base.Render(htmlWriter);
string strTableTR = createInputItem();
string html = sw.ToString() ;
//将刚才生成的Html代码插入到页面中
int startPoint = html.IndexOf("</table>", StringComparison.CurrentCultureIgnoreCase);
if(startPoint > 0)
{
html = html.Insert(startPoint, strTableTR);
}
writer.Write(html);
}