关于动态生成网页控件的疑惑
最近在设计一个可以动态生成网页的小程序,程序很简单,前台的页面如下:
只有一个按钮和一个panel
<div style="height:100px; background-color: #C0C0C0;"> 测 试 </div> <asp:Panel ID="Panel1" runat="server" Height="443px" > </asp:Panel> <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" style="height: 21px" />
private void addC() { Label labelFirstRear = new Label(); labelFirstRear.ID = "labelFirstRear"; labelFirstRear.Text = "测试" + " 你好大的单子"; labelFirstRear.Attributes.Add("style", "font-weight:bloder;font-size:18px;color:#ffffff;"); HtmlGenericControl brFirstRear = new HtmlGenericControl(); brFirstRear.TagName = "br"; HtmlGenericControl divFirstRear = new HtmlGenericControl(); divFirstRear.TagName = "div"; divFirstRear.ID = "我的div" ; divFirstRear.Attributes.Add("style", " background-color: red;"); divFirstRear.Controls.Add(labelFirstRear); divFirstRear.Controls.Add(divFirstRear); divFirstRear.Controls.Add(brFirstRear); labelFirstRear.Text = "这段内容已经结束"; divFirstRear.Controls.Add(labelFirstRear); divFirstRear.Controls.Add(brFirstRear); Panel1.Controls.Add(divFirstRear); }
<%@ Control Language="C#" ClassName="XXX" %><%@ Import Namespace="System.Drawing" %><%@ Implements Interface="IXXX" %><script runat="server"> public override void DataBind() { base.DataBind(); DropDownList1.DataBind(); } public string Name { get { var nm = ViewState["name"]; return (string)nm ?? "无名氏"; } set { if (Name != value) { ViewState["name"] = value; EnsureChildControls(); pName.DataBind(); } } } public event Action NameChanged; public string MarkedValue { get { EnsureChildControls(); return this.DropDownList1.SelectedValue; } } protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { switch (this.DropDownList1.SelectedValue) { case "标记:红": this.div.ForeColor = Color.Red; break; case "标记:蓝": this.div.ForeColor = Color.Blue; break; case "标记:黑": this.div.ForeColor = Color.Black; break; } } protected void LinkButton1_Click(object sender, EventArgs e) { Name = pName.Text; if (NameChanged != null) NameChanged(); } private List<string> GetDropdownList1Datas() { return new List<string> { "标记:黑", "标记:红", "标记:蓝" }; }</script><asp:TextBox runat="server" ID="pName" Text="<%# Name %>"></asp:TextBox>先生(女士): <asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">修改名字</asp:LinkButton><asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" DataSource="<%# GetDropdownList1Datas() %>" /><br /><asp:Panel runat="server" ID="div"> 你的合同付款期限已到,未付款<asp:TextBox runat="server" ID="pMoney" Width="60px" />元人民币,请及时付款。 <br /> <br /> XXX年XXX月XXX日</asp:Panel>