Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the value of dynamically populated controls

Tags:

c#

asp.net

I have a div Conatining a Panel in aspx page

<div id="divNameofParticipants" runat="server">
    <asp:Panel ID="panelNameofParticipants" runat="server">
    </asp:Panel>
</div>

I am populating the panel dynamically from codebehind with the following code:

void btnSubmitCountParticipant_Click(object sender, EventArgs e)
    {
        StringBuilder sbparticipantName=new StringBuilder();

        try
        {
            int numberofparticipants = Convert.ToInt32(drpNoofparticipants.SelectedValue);
            ViewState["numberofparticipants"] = numberofparticipants;
            Table tableparticipantName = new Table();
            int rowcount = 1;
            int columnCount = numberofparticipants;
            for (int i = 0; i < rowcount; i++)
            {
                TableRow row = new TableRow();
                for (int j = 0; j < columnCount; j++)
                {
                    TableCell cell = new TableCell();
                    TextBox txtNameofParticipant = new TextBox();
                    txtNameofParticipant.ID = "txtNameofParticipant" + Convert.ToString(i);
                    cell.ID = "cell" + Convert.ToString(i);
                    cell.Controls.Add(txtNameofParticipant);
                    row.Cells.Add(cell);


                }
                tableparticipantName.Rows.Add(row);
                panelNameofParticipants.Controls.Add(tableparticipantName);

            }

        }
        catch(Exception ex)
        {


        }
    }

Now I want to access the value of these dynamically generated textbox in the codebehind.for which i my code is as under:

public void CreateControls()
    {

        try
        {
            //String test1 = test.Value;
            List<string> listParticipantName = new List<string>();
            if (ViewState["numberofparticipants"] != null)
            {
                int numberofparticipants = Convert.ToInt32(ViewState["numberofparticipants"]);
                for (int i = 0; i < numberofparticipants; i++)
                {
                    string findcontrol = "txtNameofParticipant" + i;
                    TextBox txtParticipantName = (TextBox)panelNameofParticipants.FindControl(findcontrol);
                    listParticipantName.Add(txtParticipantName.Text);

                }
            }
        }
        catch (Exception ex)
        {

        }
    }

but I am not able to get the values in codebehind.

 TextBox txtParticipantName = (TextBox)panelNameofParticipants.FindControl(findcontrol);

the above code is not able to find the control and its always giving null.what am i doing wrong.i recreated the controls in page load also since postback is stateless but still no success.

Thanks in Advance

like image 639
R R Avatar asked Jun 16 '15 14:06

R R


People also ask

Which event is used to generate controls dynamically?

Retaining the dynamic controls on PostBack In order to retain the dynamic TextBoxes across PostBacks, we need to make use of Page's PreInit event to recreate the dynamic TextBoxes using the Request.

What are dynamic controls?

Dynamic control is a method to use model predictions to plan an optimized future trajectory for time-varying systems. It is often referred to as Model Predictive Control (MPC) or Dynamic Optimization.


3 Answers

You need to create dynamic controls in PreInit not in OnLoad. See documentation here: https://msdn.microsoft.com/en-us/library/ms178472.aspx

Re/Creating the controls on page load will cause the ViewState not to be bound to the controls because viewstate binding happens before OnLoad.

like image 148
Kent Cooper Avatar answered Oct 20 '22 09:10

Kent Cooper


As mentioned by other people. To create dynamic controls your need to do this for every postback and at the right time. To render dynamic controls, use the Preinit event. I suggest that your have a look at https://msdn.microsoft.com/en-us/library/ms178472(v=vs.80).aspx to learn more about this.

MSDN - PreInit: Use this event for the following: Check the IsPostBack property to determine whether this is the first time the page is being processed. Create or re-create dynamic controls. Set a master page dynamically. Set the Theme property dynamically. Read or set profile property values. NoteNote If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.

The next interesting event is Preload that states:

MSDN - PreLoad Use this event if you need to perform processing on your page or control before the Load event. After the Page raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.

Meaning that in the next event Load (Page_Load) the viewstate should be loaded, so here you should effectively be able to check your values.

You also need to make sure that view state is enabled and the easiest is probably in the page level directive:

<%@Page EnableViewState="True" %>

Take a look at the article https://msdn.microsoft.com/en-us/library/ms972976.aspx2 that goes more into the depth of all this

Note

If your problem is that you need to create controls dynamically on a button click, and there will be many controls created, you should probably turn to jQuery ajax and use the attribute [WebMethod] on a public function in your code behind. Creating dynamic controls and maintaining the ViewState is quite costly, so i really recommend this, for a better user experience.

like image 34
Binke Avatar answered Oct 20 '22 07:10

Binke


If you use a DataPresentation control like asp:GridView it will be much easier.

Markup

<asp:GridView ID="ParticipantsGrid" runat="server" AutoGenerateColumns="false">   
    <Columns>
        <asp:TemplateField HeaderText="Participants">
            <ItemTemplate>
                <asp:TextBox ID="txtNameofParticipant" runat="server" 
                    Text='<%# Container.DataItem %>'>
                </asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Code-behind

protected void btnSubmitCountParticipant_Click(object sender, EventArgs e)
{
    try
    {
        var selectedParticipantCount = Convert.ToInt32(drpNoofparticipants.SelectedValue);
        var items = Enumerable.Repeat(string.Empty, selectedParticipantCount).ToList();
        ParticipantsGrid.DataSource = items;
        ParticipantsGrid.DataBind();
    }
    catch (Exception ex)
    { }
}
public void CreateControls()
{

    try
    {
        var participants = ParticipantsGrid.Rows
            .Cast<GridViewRow>()
            .Select(row => ((TextBox)row.FindControl("txtNameofParticipant")).Text)
            .ToList();
    }
    catch (Exception ex)
    { }
}
like image 5
naveen Avatar answered Oct 20 '22 07:10

naveen