简体   繁体   中英

asp.net Recreating Dynamically Added ListBox controls on PostBack

So I almost have this working. I create Dynamic ListBoxes based on user selection. Always when the user loads the page for the first time there will only be one ListBox with the Top level categories shown (ones with no parent). I have categories with subcategories. That can be many subcategories like so

Cat 1

Cat 2

  • Cat 2.1

  • Cat 2.2

     -- Cat 2.2.1 --- Cat 2.2.1.1 

and so on.

The problem I am having is clearing the Listboxes if a user select a value from an already shown listbox. So if there are 4 Listboxes shown and the user slects a new value from the first listbox which shows that top tear categories with no parent, all Listboxes should go away and the new one should appear. If there is 4 Listboxes and the user clicks on an new item in ListbOx 3 the 4th should rerender with the subcategories to its selected parent. i hope I am explaining myself correctly.

Here is my code thus far: public partial class WebForm2 : System.Web.UI.Page { private Int32 controlCount = 0; Panel _panel;

    private Panel PanelPlaceholder
    {
        get
        {
            if (_panel == null && Master != null)
                _panel = pnlContainer;
            return _panel;
        }
    }

    protected void Page_PreInit(Object sender, EventArgs e)
    {
        this.EnsureChildControls();

        if (IsPostBack)
        {
            // Re-create controls but not from datasource
            // The controlCount value is output in the page as a hidden field during PreRender.
            controlCount = Int32.Parse(Request.Form["controlCount"]); // assigns control count from persistence medium (hidden field)
            for (Int32 i = 0; i < controlCount; i++)
            {
                CreateDynamicControlGroup(false);
            }
        }
    }
    protected void Page_Load(Object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            int cc = controlCount;

            DataTable dt = null;
            Dictionary<string, string> Params = new Dictionary<string, string>();
            dt = Globals.g_DatabaseHandler.GetRecords(StoredProcedures.GetMainCategories, Params);

            CreateDynamicControlGroup(true);

            ListBox lb = (ListBox)PanelPlaceholder.Controls[controlCount - 1];

            lb.DataSource = dt;
            lb.DataValueField = "ID";
            lb.DataTextField = "Name";
            lb.DataBind();
        }
    }


    protected void Page_PreRender(Object sender, EventArgs e)
    {
        // persist control count
        ClientScript.RegisterHiddenField("controlCount", controlCount.ToString());
    }


    private void ListBox_SelectedIndexChanged(Object sender, EventArgs e)
    {
        ListBox lb = sender as ListBox;


        Dictionary<string, string> Params = new Dictionary<string, string>();
        Params.Add("parentID", lb.SelectedValue);
        DataTable Categories = Globals.g_DatabaseHandler.GetRecords(StoredProcedures.GetChildCategories, Params);

        if (Categories.Rows.Count > 0)
        {
            CreateDynamicControlGroup(true);

            ListBox newLb = (ListBox)PanelPlaceholder.Controls[controlCount - 1];

            newLb.DataSource = Categories; // use the same table
            newLb.DataValueField = "ID";
            newLb.DataTextField = "Name";
            newLb.DataBind();
        }
    }


    private void CreateDynamicControlGroup(Boolean incrementCounter)
    {
        // Create one logical set of controls do not assign values!
        ListBox lb = new ListBox();
        lb.AutoPostBack = true;
        lb.CssClass = "panel";
        PanelPlaceholder.Controls.Add(lb);

        // wire event delegate
        lb.SelectedIndexChanged += new EventHandler(ListBox_SelectedIndexChanged);

        if (incrementCounter)
        {
            controlCount += 1;
        }
    }
}

Here is my markup:

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<div class="Column12" id="Form_NewListing">
    <h2 class="h2row">Create Your Listing - Step 1 of 2)</h2>
    <h3 class="h3row">Select a category</h3>
    <div class="panel">
        <asp:Panel ID="pnlContainer" runat="server"></asp:Panel>        

    </div>
</div>

Thanks in advance.

What about adding

int index = PanelPlaceholder.Controls.IndexOf((ListBox)sender);
for (int i = index + 1; i < PanelPlaceholder.Controls.Count; i++)
    PanelPlaceholder.Controls.RemoveAt(index + 1);

to the beginning of your ListBox_SelectedIndexChanged method?

int index = PanelPlaceholder.Controls.IndexOf((ListBox)sender);
for (int i = PanelPlaceholder.Controls.Count - 1; i > index; i--)
{
  PanelPlaceholder.Controls.RemoveAt(i);
  controlCount--;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM