以前看到MSDN的例子, 用PlaceHolder动态创建控件,
发现会生成很长的"_VIEWSTATE", 浪费性能.
现在不用PlaceHolder也可以创建控件,虽然Dropdownlist的状态会丢失.
但可以把Dropdownlist的DataSource放在Session里或再取一次
namespace DynamicUI
{
using System;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
/// <summary>
/// Summary description for WebUserControl1.
/// </summary>
public class WebUserControl1 : System.Web.UI.UserControl
{
protected System.Web.UI.WebControls.Label lblMsg;
protected System.Web.UI.WebControls.Button Button1;
private void Page_Load(object sender, System.EventArgs e)
{
for(int i=0;i<9;i++)
{
TextBox txt=new TextBox();
txt.ID ="id"+i.ToString();
if(!this.IsPostBack)
{
txt.Text ="text"+i.ToString();
}
this.Controls.Add(txt);
}
CreateDropdownlist("drpTest");
// Put user code to initialize the page here
}
private void CreateDropdownlist(string id)
{
DropDownList ctrl=new DropDownList();
ctrl.ID =id;
//if(!this.IsPostBack)
{
ctrl.Items.Add("item1");
ctrl.Items.Add("item2");
ctrl.Items.Add("item2");
ctrl.Items.Add("item3");
ctrl.Items.Add("item4");
}
ctrl.AutoPostBack =true;
ctrl.SelectedIndexChanged += new System.EventHandler(this.DropDownList1_SelectedIndexChanged);
this.Controls.Add(ctrl);
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
{
this.lblMsg.Text="test"+((DropDownList)sender).SelectedItem.Text;
}
private void Button1_Click(object sender, System.EventArgs e)
{
for(int i=0;i<9;i++)
{
TextBox txt=new TextBox();
string txtID="id"+i.ToString();
txt = this.FindControl(txtID) as TextBox;
if(txt!=null)
{
txt.Text +="Changed"+i.ToString();
}
}
}
}
}