动态生成控件
/// <summary>
/// 定义常量: 用户扩展属性的表格行,选项信息
/// </summary>
private String strTDHtmlOpionTitle = @"
<td align='left'>
({2}).<asp:Label ID='lbl{0}' runat='server' Text='{1}'></asp:Label>
</td>";
/// <summary>
/// 定义常量: 用户扩展属性的表格行 /// </summary>
private String strTDHtmlOpionNum = @"
<td width='120px'>
<asp:Label ID='lblOpionNum{0}' runat='server' Text='{1}'></asp:Label>
</td>";
/// <summary>
/// 定义常量: 用户扩展属性的表格
/// </summary>
private String strTableHtml = @"
<table cellpadding='2' cellspacing='0' border='0' width='100%'>
{0}
</table>";
protected void Page_Load(object sender, EventArgs e)
{
InitOpion(opions);
}
/// <summary>
/// 动态创建选项
/// </summary>
/// <param name="item"></param>
private void InitOpion(IList<VoteOpionInfo> opions)
{
StringBuilder sbOpionHTML = new StringBuilder();
//记录题目顺序编号
int i = 1;
foreach (VoteOpionInfo opion in opions)
{
sbOpionHTML.Append("<tr>");
//添加序号
//sbOpionHTML.AppendFormat(strTDHtmlOrderNum, new Guid(opion.OptionID).ToString("N"), i.ToString() + ".");
//添加选项内容
sbOpionHTML.AppendFormat(strTDHtmlOpionTitle, new Guid(opion.OptionID).ToString("N"), opion.OptionTitle, i.ToString());
sbOpionHTML.Append("</tr>");
i++;
}
//将控件加载到页面
string strWebHTML = string.Format(strTableHtml, sbOpionHTML);
Control objOpion = Page.ParseControl(strWebHTML);
this.pnlOpion.Controls.Add(objOpion);
}说明: (1) 在 Page_Load中不管是否是IsPostBack都需要执行InitOpion,否则在页面提交时无法获取控件的数据。
(2)使用 lbl + new Guid(opion.OptionID).ToString("N") 来作为控件的ID,以为new Guid(opion.OptionID).ToString("N") 可以取出Guid中的'-', 而且控件ID不能以数字开头。
(3) 使用Page.ParseControl()方法将html转化成控件,添加到前台。
如果页面数据需要收集,这使用FindControl("lbl" + new Guid(opion.OptionID).ToString("N"))来获取控件。



浙公网安备 33010602011771号