Partial Class _Default
    Inherits System.Web.UI.Page    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        AddAndRemoveDynamicControls()
    End Sub    Private Sub AddAndRemoveDynamicControls()
        'Determine which control fired the postback event.  
        Dim c As Control = GetPostBackControl(Page)        If Not IsNothing(c) Then
            'If the add button was clicked, increase the count to let the page know we want
            'to display an additional user control
            If c.ID.ToString = "btnAdd" Then
                ltlCount.Text = Convert.ToInt16(ltlCount.Text) + 1
            End If
        End If        'Be sure everything in the placeholder control is cleared out
        ph1.Controls.Clear()        Dim ControlID As Integer = 0        'Since these are dynamic user controls, re-add them every time the page loads.
        For i As Integer = 0 To (Convert.ToInt16(ltlCount.Text) - 1)
            Dim DynamicUserControl As WebUserControl = LoadControl("WebUserControl.ascx")
            'If this particular control id has been deleted from the page, DO NOT use it again.  If we do, it will
            'pick up the viewstate data from the old item that had this control id, instead of generating
            'a completely new control.  Instead, increment the control id so we're guaranteed to get a "new"
            'control that doesn't have any lingering information in the viewstate.            
            While InDeletedList("uc" & ControlID) = True
                ControlID += 1
            End While            'Note that if the item has not been deleted from the page, we DO want it to use the same control id
            'as it used before, so it will automatically maintain the viewstate information of the user control
            'for us.
            DynamicUserControl.ID = "uc" & ControlID            'Add an event handler to this control to raise an event when the delete button is clicked
            'on the user control
            AddHandler DynamicUserControl.RemoveUserControl, AddressOf Me.HandleRemoveUserControl            'Finally, add the user control to the panel
            ph1.Controls.Add(DynamicUserControl)            'Increment the control id for the next round through the loop
            ControlID += 1
        Next
    End Sub    Private Function InDeletedList(ByVal ControlID As String) As Boolean
        'Determine if the passed in user control id has been stored in the list of controls that
        'were previously deleted off the page
        Dim DeletedList() As String = ltlRemoved.Text.Split("|")
        For i As Integer = 0 To DeletedList.GetLength(0) - 1
            If ControlID.ToLower = DeletedList(i).ToLower Then
                Return True
            End If
        Next
        Return False
    End Function    Sub HandleRemoveUserControl(ByVal sender As Object, ByVal e As EventArgs)
        'This handles delete event fired from the user control        'Get the user control that fired this event, and remove it
        Dim DynamicUserControl As WebUserControl = sender.parent
        ph1.Controls.Remove(sender.parent)        'Keep a pipe delimited list of which user controls were removed.  This will increase the 
        'viewstate size if the user keeps removing dynamic controls, but under normal use
        'this is such a small increase in size that it shouldn't be an issue.
        ltlRemoved.Text &= DynamicUserControl.ID & "|"        'Also, now that we've removed a user control decrement the count of total user controls on the page
        ltlCount.Text = Convert.ToInt16(ltlCount.Text) - 1
    End Sub
    Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        'Handled in page load
    End Sub
    Protected Sub btnDisplayValues_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDisplayValues.Click
        ltlValues.Text = ""
        For Each c As Control In ph1.Controls
            'Find the specific user control that we added to this placeholder, and then get the selected values
            'for the dropdownlist, checkbox, and textbox and print them to the screen.
            If c.GetType.Name.ToLower = "webusercontrol_ascx" Then
                Dim uc As UserControl = CType(c, UserControl)
                Dim tbx1 As TextBox = uc.FindControl("tbx1")
                Dim ddl1 As DropDownList = uc.FindControl("ddl1")
                Dim cbx1 As CheckBoxList = uc.FindControl("cbx1")                Dim sb As New System.Text.StringBuilder
                sb.Append("Textbox value: " & tbx1.Text & "<br />")
                sb.Append("Dropdown value: " & ddl1.SelectedValue & "<br />")
                sb.AppendLine("Checkbox values: ")                For Each li As ListItem In cbx1.Items
                    If li.Selected = True Then
                        sb.Append(li.Value & "<br />")
                    End If
                Next                sb.Append("<hr />")                ltlValues.Text &= sb.ToString
            End If
        Next
    End Sub
    'Find the control that caused the postback.
    'I got this code from http://www.ryanfarley.com/blog/archive/2005/03/11/1886.aspx
    Public Function GetPostBackControl(ByVal page As Page) As Control
        Dim control As Control = Nothing        Dim ctrlname As String = page.Request.Params.[Get]("__EVENTTARGET")
        If Not IsNothing(ctrlname) And ctrlname <> String.Empty Then
            control = page.FindControl(ctrlname)
        Else
            For Each ctl As String In page.Request.Form
                Dim c As Control = page.FindControl(ctl)
                If TypeOf c Is System.Web.UI.WebControls.Button Then
                    control = c
                    Exit For
                End If
            Next
        End If
        Return control
    End FunctionEnd Class

解决方案 »

  1.   


    using Microsoft.VisualBasic;
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Data;
    using System.Diagnostics;partial class _Default : System.Web.UI.Page
    { protected void Page_Load(object sender, System.EventArgs e)
    {
    AddAndRemoveDynamicControls();
    } private void AddAndRemoveDynamicControls()
    {
    //Determine which control fired the postback event.   
    Control c = GetPostBackControl(Page); if ((c != null)) {
    //If the add button was clicked, increase the count to let the page know we want
    //to display an additional user control
    if (c.ID.ToString == "btnAdd") {
    ltlCount.Text = Convert.ToInt16(ltlCount.Text) + 1;
    }
    } //Be sure everything in the placeholder control is cleared out
    ph1.Controls.Clear(); int ControlID = 0; //Since these are dynamic user controls, re-add them every time the page loads.
    for (int i = 0; i <= (Convert.ToInt16(ltlCount.Text) - 1); i++) {
    WebUserControl DynamicUserControl = LoadControl("WebUserControl.ascx");
    //If this particular control id has been deleted from the page, DO NOT use it again. If we do, it will
    //pick up the viewstate data from the old item that had this control id, instead of generating
    //a completely new control. Instead, increment the control id so we're guaranteed to get a "new"
    //control that doesn't have any lingering information in the viewstate.   
    while (InDeletedList("uc" + ControlID) == true) {
    ControlID += 1;
    } //Note that if the item has not been deleted from the page, we DO want it to use the same control id
    //as it used before, so it will automatically maintain the viewstate information of the user control
    //for us.
    DynamicUserControl.ID = "uc" + ControlID; //Add an event handler to this control to raise an event when the delete button is clicked
    //on the user control
    DynamicUserControl.RemoveUserControl += this.HandleRemoveUserControl; //Finally, add the user control to the panel
    ph1.Controls.Add(DynamicUserControl); //Increment the control id for the next round through the loop
    ControlID += 1;
    }
    } private bool InDeletedList(string ControlID)
    {
    //Determine if the passed in user control id has been stored in the list of controls that
    //were previously deleted off the page
    string[] DeletedList = ltlRemoved.Text.Split("|");
    for (int i = 0; i <= DeletedList.GetLength(0) - 1; i++) {
    if (ControlID.ToLower() == DeletedList[i].ToLower()) {
    return true;
    }
    }
    return false;
    } public void HandleRemoveUserControl(object sender, EventArgs e)
    {
    //This handles delete event fired from the user control //Get the user control that fired this event, and remove it
    WebUserControl DynamicUserControl = sender.parent;
    ph1.Controls.Remove(sender.parent); //Keep a pipe delimited list of which user controls were removed. This will increase the  
    //viewstate size if the user keeps removing dynamic controls, but under normal use
    //this is such a small increase in size that it shouldn't be an issue.
    ltlRemoved.Text += DynamicUserControl.ID + "|"; //Also, now that we've removed a user control decrement the count of total user controls on the page
    ltlCount.Text = Convert.ToInt16(ltlCount.Text) - 1;
    }
    protected void btnAdd_Click(object sender, System.EventArgs e)
    {
    //Handled in page load
    }
    protected void btnDisplayValues_Click(object sender, System.EventArgs e)
    {
    ltlValues.Text = "";
    foreach (Control c in ph1.Controls) {
    //Find the specific user control that we added to this placeholder, and then get the selected values
    //for the dropdownlist, checkbox, and textbox and print them to the screen.
    if (c.GetType.Name.ToLower == "webusercontrol_ascx") {
    UserControl uc = (UserControl)c;
    TextBox tbx1 = uc.FindControl("tbx1");
    DropDownList ddl1 = uc.FindControl("ddl1");
    CheckBoxList cbx1 = uc.FindControl("cbx1"); System.Text.StringBuilder sb = new System.Text.StringBuilder();
    sb.Append("Textbox value: " + tbx1.Text + "<br />");
    sb.Append("Dropdown value: " + ddl1.SelectedValue + "<br />");
    sb.AppendLine("Checkbox values: "); foreach (ListItem li in cbx1.Items) {
    if (li.Selected == true) {
    sb.Append(li.Value + "<br />");
    }
    } sb.Append("<hr />"); ltlValues.Text += sb.ToString();
    }
    }
    }
    //Find the control that caused the postback.
    //I got this code from http://www.ryanfarley.com/blog/archive/2005/03/11/1886.aspx
    public Control GetPostBackControl(Page page)
    {
    Control control = null; string ctrlname = page.Request.Params.Get("__EVENTTARGET");
    if ((ctrlname != null) & ctrlname != string.Empty) {
    control = page.FindControl(ctrlname);
    } else {
    foreach (string ctl in page.Request.Form) {
    Control c = page.FindControl(ctl);
    if (c is System.Web.UI.WebControls.Button) {
    control = c;
    break; // TODO: might not be correct. Was : Exit For
    }
    }
    }
    return control;
    }
    public _Default()
    {
    Load += Page_Load;
    }}
      

  2.   

    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            AddAndRemoveDynamicControls();
        }
        private void AddAndRemoveDynamicControls()
        {
            //'Determine which control fired the postback event.   
            Control c = GetPostBackControl(Page);        if (c != null)
            {
                //'If the add button was clicked, increase the count to let the page know we want
                //'to display an additional user control
                if (c.ID == "btnAdd")
                    ltlCount.Text = (Convert.ToInt16(ltlCount.Text) + 1).ToString();
            }        //'Be sure everything in the placeholder control is cleared out
            ph1.Controls.Clear();        int ControlID = 0;        //'Since these are dynamic user controls, re-add them every time the page loads.
            for (int i = 0; i <= (Convert.ToInt16(ltlCount.Text) - 1); i++)
            {
                WebUserControl DynamicUserControl = LoadControl("WebUserControl.ascx");
                //'If this particular control id has been deleted from the page, DO NOT use it again. If we do, it will
                // 'pick up the viewstate data from the old item that had this control id, instead of generating
                // 'a completely new control. Instead, increment the control id so we're guaranteed to get a "new"
                //'control that doesn't have any lingering information in the viewstate.   
                while (InDeletedList("uc" + ControlID))
                {
                    ControlID += 1;
                }            //'Note that if the item has not been deleted from the page, we DO want it to use the same control id
                //'as it used before, so it will automatically maintain the viewstate information of the user control
                //'for us.
                DynamicUserControl.ID = "uc" + ControlID;            //'Add an event handler to this control to raise an event when the delete button is clicked
                //'on the user control
                DynamicUserControl.RemoveUserControl += new EventHandler(this.HandleRemoveUserControl);            // 'Finally, add the user control to the panel
                ph1.Controls.Add(DynamicUserControl);            //'Increment the control id for the next round through the loop
                ControlID += 1;
            }
        }
        private bool InDeletedList(string ControlID)
        {
            //'Determine if the passed in user control id has been stored in the list of controls that
            //'were previously deleted off the page
            string[] DeletedList = ltlRemoved.Text.Split("|");
            for (int i = 0; i <= DeletedList.GetLength(0) - 1; i++)
            {
                if (ControlID.ToLower() == DeletedList[i].ToLower())
                    return true;
            }
            return false;
        }
        void HandleRemoveUserControl(object sender, EventArgs e)
        {
            //'This handles delete event fired from the user control        //'Get the user control that fired this event, and remove it
            WebUserControl DynamicUserControl = ((Control)sender).Parent;
            ph1.Controls.Remove(DynamicUserControl);        //'Keep a pipe delimited list of which user controls were removed. This will increase the  
            //'viewstate size if the user keeps removing dynamic controls, but under normal use
            //'this is such a small increase in size that it shouldn't be an issue.
            ltlRemoved.Text += DynamicUserControl.ID + "|";        //'Also, now that we've removed a user control decrement the count of total user controls on the page
            ltlCount.Text = (Convert.ToInt16(ltlCount.Text) - 1).ToString();
        }
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            // 'Handled in page load
        }
        protected void btnDisplayValues_Click(object sender, EventArgs e)
        {
            ltlValues.Text = "";
            foreach (Control c in ph1.Controls)
            {
                // 'Find the specific user control that we added to this placeholder, and then get the selected values
                //'for the dropdownlist, checkbox, and textbox and print them to the screen.
                if (c.GetType().Name.ToLower() == "webusercontrol_ascx")
                {
                    UserControl uc = (UserControl)c;
                    TextBox tbx1 = uc.FindControl("tbx1") as TextBox;
                    DropDownList ddl1 = uc.FindControl("ddl1") as DropDownList;
                    CheckBoxList cbx1 = uc.FindControl("cbx1") as CheckBoxList;                System.Text.StringBuilder sb;
                    sb.Append("Textbox value: " + tbx1.Text + "<br />");
                    sb.Append("Dropdown value: " + ddl1.SelectedValue + "<br />");
                    sb.AppendLine("Checkbox values: ");                foreach (ListItem li in cbx1.Items)
                        if (li.Selected)
                            sb.Append(li.Value + "<br />");                sb.Append("<hr />");                ltlValues.Text += sb.ToString;
                }
            }
        }
        // 'Find the control that caused the postback.
        //'I got this code from http://www.ryanfarley.com/blog/archive/2005/03/11/1886.aspx
        public Control GetPostBackControl(Page page)
        {
            Control control = null;        string ctrlname = page.Request.Params["__EVENTTARGET"].ToString();
            if (ctrlname != null && ctrlname != String.Empty)
                control = page.FindControl(ctrlname);
            else
                foreach (string ctl in page.Request.Form)
                {
                    Control c = page.FindControl(ctl);
                    if (c is System.Web.UI.WebControls.Button)
                    {
                        control = c;
                        break;
                    }
                }
            return control;
        }
    }