動態產生控制項!?

摘要:動態產生控制項!?

因為常遇到這種問題,但Google裡的文章又沒有很確實的做法,於是今天做了一個小小的實驗

首先,我們先建立一個網站,然後新增一個webControl控制項,這個控制項主要負責,動態新增N個TextBox
而為了保留值,所以我們必需把code寫在Page_load 或OnInit中,程式碼如下:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


public partial class WebUserControl : System.Web.UI.UserControl
{
    private int controlsValue=0;
    TextBox tb;

    public int ControlsValue
    {
        get { return controlsValue; }
        set { controlsValue = value; }
    }


    protected override void OnInit(EventArgs e)
    {
        for (int i = 0; i < controlsValue; i++)
        {
            tb = new TextBox();
            tb.ID = "text_" + i.ToString();
            tb.Text = i.ToString();
            this.Controls.Add(tb);
        }

    }




    protected void Page_Load(object sender, EventArgs e)
    {

    }

}

接下來新增一個WebPage,直接看程式碼:
 

using System;
using System.Web.UI;
using System.Web.UI.WebControls;



public partial class Default2 : System.Web.UI.Page
{
    Control c;
    protected void Page_Load(object sender, EventArgs e)
    {
        String val = TextBox1.Text;
        if (val != "")
        {
            int tbVal=0;
            bool rtn = int.TryParse(val, out tbVal);
            if (rtn)
            {
                c = LoadControl("WebUserControl.ascx");
                //用Reflection設定WebControl的方法
                c.GetType().InvokeMember("ControlsValue", System.Reflection.BindingFlags.SetProperty, null, c, new object[] { tbVal });
                PlaceHolder1.Controls.Add(c);
            }

        }
        
    }


    protected void Button1_Click(object sender, EventArgs e)
    {
        if (PlaceHolder1.HasControls())
            Response.Write("控制項還在");
        else
            Response.Write("控制項不在");
    }


    protected void Button2_Click(object sender, EventArgs e)
    {
        if (c != null)
        {

            PlaceHolder1.Controls.Add(c);
        }

    }


    /// <summary>
    /// 拿取TextBox所有的值,用逗號分開
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>

    protected void Button3_Click(object sender, EventArgs e)
    {
        string temp = "";
        if (c != null)
        {
            if (c.HasControls())
            {
                //拿取Control
                ControlCollection c1 = c.Controls;
                foreach (Control item in c1)
                {
                    //判斷控制項為TextBox Control
                    if (item.GetType().ToString() == "System.Web.UI.WebControls.TextBox")
                    {
                        temp += ((TextBox)item).Text + ",";
                    }

                }

            }

        }


        Label1.Text = temp;
    }

}

顯示畫面:

  實驗結果:
  先輸入控制項數量,按查詢,然後在取值後,可以發現資料存在!