有時候在項目中需要根據實際傳過來的參數來產生不同個數的控制項來擺放在頁面上,這時候可以重寫頁面 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);
}