Search code examples
c#asp.netdynamic-controls

C# dynamically created control issue


i'm having issues retreiving the values out of a dynamically created dropdownlist. all controls are created in the Page_Init section. the listitems are added at that time as well from an array of listitems. (the controls are named the same so should be accessable to the viewstate for appropriate setting.)

here is the function that attempts to retrieve the values:

protected void Eng98AssignmentComplete_Click(object sender, EventArgs e)
{
    String myID = "0";
    Page page = Page;
    Control postbackControlInstance = null;
    // handle the Button control postbacks
    for (int i = 0; i < page.Request.Form.Keys.Count; i++)
    {
        postbackControlInstance = page.FindControl(page.Request.Form.Keys[i]);
        //Response.Write(page.Request.Form.Keys[i].ToString());
        if (postbackControlInstance is System.Web.UI.WebControls.Button)
        {
            myID = Convert.ToString(
                postbackControlInstance.ID.Replace("button_", ""));
        }
    }
    String txtholder = "ctl00$ContentPlaceHolder$Eng098Instructors_" + myID;
    Response.Write("MYID: " + myID + "<br/>");
    DropDownList ddInstructorCheck = (DropDownList)Page.FindControl(txtholder);
    Response.Write("Instructor Selected: "
      + ddInstructorCheck.SelectedValue + "<br/>");
}

here is the output I get, no matter which instructor was selected.....

MYID: 1_1
Instructor Selected: 0
ctl00$ContentPlaceHolder$Eng098Instructors_1_1

the name of the control is correct (verified via view source)....

ideas?


Solution

  • I had 2 catches.... here's what they were.

    1.  I didn't clear the table I was adding to before re-creating the controls.
    

    apparently my attention to detail was off yesterday, i'm pretty sure the ctlXX frontrunner of the control was some different number upon postback due to how I was recreating the controls.

    2.  I was assigning the same list to all the dropdownlist controls.  
    

    once I called the lookup upon each creation a dropdownlist control, all works well.

    anyway for what it's worth....