Search code examples
c#asp.net.netascx

Getting value from dynamically added controls from ascx.file


I have a question regarding catching my values from dropdownlists and textboxes and saving them to my database.

I'm using ASP.NET aspx pages, not MVC.

I have one ascx file with my controls in it. I am creating them dynamically in my code. I do not have problem with postback, I'm using ViewState as a counter from my controls. Every control is given an ID of "ratingcontrols" + viewState counter. so, for example i have 6 dropdownlists and 4 textboxes, counter goes from 0 to 8. First dropdownlist has am ID "ratingcontrols0", second "ratingcontrols1" and so on. My first 3 dropdownlists are actualy separated day, month and year, it represents my calendar. Next 3 dropdownlists are my second calendar.

When I click on a button to add controls, these 10 controls are created as a group from my ascx file. When I click second time on a button, I have another group of 10 controls, just now my counter goes from 9 to 17 for my IDs.

My question is, how to get those values, and add each group to my database and how to connect each group of 3 dropdownlists into a date with selected values?


Solution

  • The following code has worked for me:

    public Control FindControlRecursivelyByID(Control controlToSearch, string controlToFind)
    {
        Control rtnCtrl = null;
        foreach (Control ctrl in controlToSearch.Controls) {
            if (ctrl != null && ctrl.ID == controlToFind) {
                rtnCtrl = ctrl;
            } else {
                if (ctrl.HasControls & rtnCtrl == null) {
                    rtnCtrl = FindControlRecursivelyByID(ctrl, controlToFind);
                }
            }
        }
        return rtnCtrl;
    }
    

    When calling this method, you must do a directcast also:

    ((TextBox)FindControlRecursivelyByID(this.Page, "controlID")).Text == "SomeText"