动态生成服务器控件

public partial class _Default : System.Web.UI.Page
{
 
 
 
    private static Dictionary<string ,string> di=new Dictionary<string ,string>();
    protected void Page_Load(object sender, EventArgs e)
    {
        //自动生成刷新页面前的动态控件
        if (!this.IsPostBack)
        {
            ViewState.Add("count", 0);
            di.Clear();
        }
        else
        {
            int i=0;
            foreach (KeyValuePair<string, string> pair in di)
            {
                if(pair.Key=="TextBox")
                {
                    this.PlaceHolder2.Controls.Add(new LiteralControl("TextBox" + i + " :"));
                     TextBox tb = new TextBox();
                    tb.ID = "TextBox" + i;
                    this.PlaceHolder2.Controls.Add(tb);
                    i++;
                }
                else               
                {
                    this.PlaceHolder2.Controls.Add(new LiteralControl("DropDownList" + i+ " :"));
                    DropDownList ddl = new DropDownList();
                    ListItem li = new ListItem("123", "123");
                    ddl.Items.Add(li);
                    this.PlaceHolder2.Controls.Add(ddl);
                    i++;
                }
            }

 

        }

    }
    private void CreateControl(int number)
    {

 


    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        int Max = 0;
        for (int i = 0; i < Int32.Parse(ViewState["count"].ToString()); i++)
        {
            Max += Int32.Parse((this.FindControl("Textbox" + i) as TextBox).Text);
        }


    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        this.PlaceHolder2.Controls.Add(new LiteralControl("TextBox" + ViewState["count"].ToString() + " :"));
        TextBox tb = new TextBox();
        tb.ID = "TextBox" + ViewState["count"].ToString();
        this.PlaceHolder2.Controls.Add(tb);
        ViewState["count"] = Int32.Parse(ViewState["count"].ToString()) + 1;
        di.Add("TextBox", ViewState["count"].ToString());

        this.PlaceHolder2.Controls.Add(new LiteralControl("DropDownList" + ViewState["count"].ToString() + " :"));
         DropDownList ddl = new DropDownList();
         ListItem li = new ListItem("123","123");
         ddl.Items.Add(li);
         ddl.ID = "DropDownList" + ViewState["count"].ToString();
         this.PlaceHolder2.Controls.Add(ddl);
         ViewState["count"] = Int32.Parse(ViewState["count"].ToString()) + 1;
         di.Add("DropDownList", ViewState["count"].ToString());

    }

posted on 2016-05-17 08:20  张林春  阅读(172)  评论(0编辑  收藏  举报