要動態產生控制項並保留其狀態(值),必須依賴網站的變數

,如Session、ViewState等...

此例以ViewState方式,並模擬ASP.NET的Postback機制,控制產生的控制項

 

html:


<span>產生</span><asp:TextBox ID="txtCount" runat="server"></asp:TextBox>

<span>個textBox</span>


<asp:Button ID="btnAction" runat="server" Text="產生" onclick="btnAction_Click" />

    <asp:Panel ID="panelZone" runat="server">

    </asp:Panel>

<asp:Button ID="btnCheck" runat="server" Text="確認" onclick="btnCheck_Click" />


aspx.cs部分:

//運用asp.net的模式!,將上次postback前產生的控制項,再次還原

    protected void Page_Load(object sender, EventArgs e)

    {

        if (ViewState["Ctl_count"] != null)

            addTextBox();

    }

    //啟用ViewState紀錄動態產生控制項

    protected override void LoadViewState(object savedState)

    {

        base.LoadViewState(savedState);

    }

    protected void btnAction_Click(object sender, EventArgs e)

    {

        int count =Convert .ToInt32 ( txtCount.Text);

        ViewState["Ctl_count"] = count;

        addTextBox();

    }

    protected void btnCheck_Click(object sender, EventArgs e)

    {

        string str = "";

        foreach (Control ctl in panelZone.Controls)

        {

            string type = ctl.GetType().ToString();

            if (ctl.GetType().ToString() == "System.Web.UI.WebControls.TextBox")

            {

                TextBox txt = (TextBox)ctl;

                str +=txt.ID +":"+ txt.Text+"</br>";

            }

        }

        Response.Write(str );

    }

    void addTextBox()

    {

        int count = Convert.ToInt32( ViewState["Ctl_count"]);

        for (int i = 0; i <= count - 1; i++)

        {

            TextBox txt = new TextBox();

            int index = (i + 1);

            string id =  "txt" + index;

            txt.ID =id;

            SetText(txt);

            if (ViewState[id] == null)

                txt.Text = string.Empty;

            else

                txt.Text = ViewState[id].ToString ();

            panelZone.Controls.Add(txt);

            panelZone.Controls.Add(new LiteralControl("</br>"));

        }

        //啟動ViewState紀錄

        ViewState["controsladded"] = true;

    }

    //將控制項的值(或狀態),紀錄於ViewState,以供下次Postback調用

    void SetText(object s)

    {

        TextBox txt = (TextBox)s;

        string text = txt.Text;

        string id = txt.ID;

        ViewState[id] = text;

    }

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Ryan 的頭像
    Ryan

    Ryan的blog

    Ryan 發表在 痞客邦 留言(1) 人氣()