Dynamically added control to placeholder c# asp.net 2.0
Posted on 2007-03-23
I want to dynamically add a control to an aspx page. I use ajax. I only know the number of controls and what type they are at runtime (only textboxes and dropdowns)
I have three placeholders on my page, they are static.
I have a function that tries to add controls dynamically to these placeholders, but the bum out with an error saying "object reference not set to an instance of an object"
This is the function:
public void GenDropDown()
DropDownList dl = new DropDownList();
dl.DataSource = GetConfigurationList(4);
dl.ID = "1";
dl.DataTextField = "ChoiceDisplayedValue";
dl.DataValueField = "ConfigurationAttributeChoiceId";
PlaceHolder myPlaceHolder = (PlaceHolder)Page.FindControl("ph1");
This function works fine untill the last line, dl contains a dropdown with several items, but when I add it it complains with the error above.
I think this is related to the fact that the controls are not predefined from what I have found online.
I am open to suggestions if the example above is not workable.
I have fiddled with LoadControl, but I don't know how to use it for a webcontrol, it only seems to work for user defined controls (ascx).
Any help appreciated!.