Click here to Skip to main content
15,894,410 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have given code for adding dynamic Control below , how to get value from this
C#
DropDownList ddlAgent = new DropDownList();
                    ddlAgent.EnableViewState = false;
                    ddlAgent.CssClass = "RegsSelect";
                    ddlAgent.ID = "ddlAgent";
                    ddlAgent.ClientIDMode = ClientIDMode.Static;
                    ddlAgent.Attributes.Add("style", "margin-left:-4px;height:40px;width:328px;");
                    upText.ContentTemplateContainer.Controls.Add(ddlAgent);

                    //Binding data with dropdownlist
                    CUser objUser = new CUser();
                    ddlAgent.DataSource = objUser.GetUserByRoleId(4);
                    ddlAgent.DataValueField = "Id";
                    ddlAgent.DataTextField = "FirstName";
                    ddlAgent.DataBind();
now to get control
C#
DropDownList ddlAgent=(DropDownList) upText.ContentTemplateContainer.FindControl("ddlAgent");
which gives Null Reference Exception

it is created from selected index of previous dropdownlist and it is placed in updatepanel
Posted
Updated 5-May-13 22:43pm
v2

1 solution

Always create your dynamic control in Page_Init event (Read this[^] and this[^] for a detailed information).
Change your CS. Try this:
C#
//Create the controls in this page event
protected void Page_Init(object sender, EventArgs e)
{
    DropDownList ddlAgent = new DropDownList();
    ddlAgent.EnableViewState = false;
    ddlAgent.CssClass = "RegsSelect";
    ddlAgent.ID = "ddlAgent";
    ddlAgent.ClientIDMode = ClientIDMode.Static;
    ddlAgent.Attributes.Add("style", "margin-left:-4px;height:40px;width:328px;");
    upText.ContentTemplateContainer.Controls.Add(ddlAgent);
}

Now, find the control and bind it in your function or method. Try this:
C#
DropDownList ddlAgent=(DropDownList) upText.ContentTemplateContainer.FindControl("ddlAgent"); //Now you won't get a null referance exception
//Binding data with dropdownlist
CUser objUser = new CUser();
ddlAgent.DataSource = objUser.GetUserByRoleId(4);
ddlAgent.DataValueField = "Id";
ddlAgent.DataTextField = "FirstName";
ddlAgent.DataBind();



--Amit
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900