Add dynamic controls & save contols values

  • (2 Pages)
  • +
  • 1
  • 2

20 Replies - 8794 Views - Last Post: 28 August 2013 - 05:03 AM Rate Topic: -----

#1 staindromeo  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 153
  • Joined: 21-October 10

Add dynamic controls & save contols values

Posted 19 August 2013 - 04:17 PM

Hello,

I'm trying to add multiple rows of textbox controls and datepickers triggered by an 'Add' button. The 'Add' button adds the required controls once, but when I click on 'Add' a second time it refreshes the control to blank and an additional row with the controls isn't added.

Here's my code: (.cs)
 protected void AddNewOpenedCompetitor_Click(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
        {
            UpdatePanel DrpUpdate = new UpdatePanel();
            DrpUpdate.UpdateMode = UpdatePanelUpdateMode.Conditional;
            DrpUpdate.RenderMode = UpdatePanelRenderMode.Inline;

            DropDownList DrLst = new DropDownList();
            DrLst.SelectedIndexChanged += new EventHandler(AddOtherCompetitor);
            DrLst.AutoPostBack = true;

            TextBox NewCompTextBx = new TextBox();
            NewCompTextBx.ID = "NewCompetitorStringName";
            NewCompTextBx.CssClass = "TextBoxWidth";

            Page.RegisterStartupScript("Script3", "<script type=\"text/javascript\">$(\"#" + NewCompTextBx.ClientID + "\" ).datepicker({showOn: \"button\",buttonImage: \"images/NewCalendar.png\",buttonImageOnly: true});</script>");

            ImageButton DeleteNewComp = new ImageButton();
            DeleteNewComp.ImageUrl = "images/DeleteCross.png";
            DeleteNewComp.ID = "AddNComp";
            DeleteNewComp.Click += delegate { DeleteCompetitors(DrLst.ClientID.ToString(), NewCompTextBx.ClientID.ToString(), DeleteNewComp.ClientID.ToString()); };

            Image Spacer = new Image();
            Spacer.ImageUrl = "images/transpix.gif";

            DrpUpdate.ContentTemplateContainer.Controls.Add(DrLst);
            AddNewCompetitor.Controls.Add(DrpUpdate);
AddNewCompetitor.Controls.Add(NewCompTextBx);
            AddNewCompetitor.Controls.Add(DeleteNewComp);
            LoadDrpDownList(DrLst.ClientID.ToString());

ShowHideAllDivs();
}
    }

  public void ShowHideAllDivs()
    {
        if (Page.IsPostBack)
        {
            //Page.RegisterStartupScript("Script1", "<script type=\"text/javascript\">function ShowAllOpen(){var MyString = document.getElementById('" + OpenDivs.ClientID + "').value;if(MyString != ''){var MySplitString = MyString.split(',');for(i=0; i< MySplitString.length; i++){document.getElementById(MySplitString[i]).style.display = 'block'; }}}ShowAllOpen();</script>");
            Page.RegisterStartupScript("Script1", "<script type=\"text/javascript\">function ShowAllOpen(){var MyString = document.getElementById('" + DivsPool.ClientID + "').value;var MySplitStringX = MyString.split(',');for(i=0; i< MySplitStringX.length-1; i+=2){if(MySplitStringX[i+1] == '1'){document.getElementById(MySplitStringX[i]).style.display = 'block';}else {document.getElementById(MySplitStringX[i]).style.display = 'none';}}}ShowAllOpen();</script>");
        }
    }



.Aspx page:
<div id="CompStoreOpenedDiv" style="display: none; width: 600px; height: auto; border: 1px solid black;
                                                padding: 20px 20px 20px 20px;">
                                                <table border="0" bordercolor="yellow" width="80%" align="center">
                                                    <tr>
                                                        <td valign="top">
                                                            New competitor store:
                                                        </td>
                                                        <td align="left">
                                                            <asp:UpdatePanel ID="xx1" runat="server" UpdateMode="Conditional" RenderMode="Inline">
                                                                <ContentTemplate>
                                                                    <asp:DropDownList runat="server" ID="NewCompetitors" onselectedIndexChanged="AddOtherCompetitor"
                                                                        AutoPostBack="true">
                                                                    </asp:DropDownList>
                                                                </ContentTemplate>
                                                            </asp:UpdatePanel>
                                                            <asp:TextBox CssClass="TextBoxWidth" runat="server" ID="NewCompetitorsOpenedDate">
                                                            </asp:TextBox>
                                                            <asp:Panel runat="server" ID="AddNewCompetitor" Visible="true">
                                                            </asp:Panel>
                                                            <br />
                                                            <asp:Button runat="server" ID="AddNewOpenedCompetitor" Text="Add" onclick="AddNewOpenedCompetitor_Click" />
                                                        </td>
                                                    </tr>
                                                </table>
                                            </div>



Any ideas on how I should go about this?

Is This A Good Question/Topic? 0
  • +

Replies To: Add dynamic controls & save contols values

#2 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3552
  • View blog
  • Posts: 11,008
  • Joined: 05-May 12

Re: Add dynamic controls & save contols values

Posted 19 August 2013 - 06:29 PM

Looks like your question was already answered in your other post: http://forums.asp.ne...ontrol+s+values
Was This Post Helpful? 0
  • +
  • -

#3 staindromeo  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 153
  • Joined: 21-October 10

Re: Add dynamic controls & save contols values

Posted 20 August 2013 - 07:21 AM

I tried this

protected override void onload(EventArgs e)
    {
        base.onload(e);
        AddNewOpenedCompetitor.Click += new EventHandler(AddNewOpenedCompetitor_Click);

    }



And I get the error that multiple controls have the same ID.
Was This Post Helpful? 0
  • +
  • -

#4 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3552
  • View blog
  • Posts: 11,008
  • Joined: 05-May 12

Re: Add dynamic controls & save contols values

Posted 20 August 2013 - 05:28 PM

I think that you added more than just that because that code change would not have caused duplicate IDs. Additionally, that change to register for events is redundant to your line of code that says:
<asp:Button runat="server" ID="AddNewOpenedCompetitor" Text="Add" onclick="AddNewOpenedCompetitor_Click" />


Was This Post Helpful? 0
  • +
  • -

#5 Nakor  Icon User is offline

  • Professional Lurker
  • member icon

Reputation: 444
  • View blog
  • Posts: 1,492
  • Joined: 28-April 09

Re: Add dynamic controls & save contols values

Posted 20 August 2013 - 07:54 PM

The problem is that dynamically added controls are not maintained across postbacks without you manually reloading them. You need to keep track of how many times you've added controls and then on postback recreate that number of controls. Also, in order for the values and states of the controls to be maintained you need to be sure that you are giving the controls the same ID each time that they are created. The easiest way to do that is just to append the number that you are tracking to the controls. So if you have 5 groups of controls the first group would have ID's ending in 1, the second group would end in 2 and so on. However, the best way to handle adding multiple controls the page at once is to put all of those controls into a UserControl and then you only have to add a single control to your page on each postback instead of 5 or 6.

Here's a quick example. First the UserControl. I'm not doing anything in the code behind since this is just an example so I won't be showing the .cs file for it.

Spoiler

Now, the .aspx page. I use a PlaceHolder control to add the UserControls into the page.

Spoiler


Finally, the .aspx.cs file. Here, I maintain a count of controls using ViewState. On each Page_Load I use the ControlCount to loop through and recreate the controls I have already added. This needs to be done in the Page_Load event so that the state and values of the controls can be reapplied.

Spoiler


Edit: Updated the .cs file. Needs to load the controls in the Page_Load to maintain state. Added spoiler tags

Attached Image

Attached Image

This post has been edited by Nakor: 20 August 2013 - 08:13 PM

Was This Post Helpful? 2
  • +
  • -

#6 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4468
  • View blog
  • Posts: 7,780
  • Joined: 08-June 10

Re: Add dynamic controls & save contols values

Posted 21 August 2013 - 07:10 AM

Great post Nakor. I'm going to move this to the ASP.NET section.
Was This Post Helpful? 0
  • +
  • -

#7 staindromeo  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 153
  • Joined: 21-October 10

Re: Add dynamic controls & save contols values

Posted 21 August 2013 - 08:15 AM

Thanks for the help Nakor, I am just trying to figure out how this can be integrated with what I currently have. I think the main issue is maintaining the viewstate of the dynamically created controls across postback. Creating a usercontrol isn't an option as I have other dynamic controls across the page, creating controls for each one isn't a route I want to go right now but yeah you're right it makes it easier to count how many times it needs to be added on page load.

Also the dropdownlist is populated by an Array, so when I create the eventhandler OnIt or Page_PreInit, the dropdownlist control errors out with the multiple controls have the same ID error.

Thanks everyone for the help so far.
Was This Post Helpful? 0
  • +
  • -

#8 staindromeo  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 153
  • Joined: 21-October 10

Re: Add dynamic controls & save contols values

Posted 21 August 2013 - 12:53 PM

Alright looks like I am going to be creating a user control after all :online2long:

This post has been edited by staindromeo: 21 August 2013 - 01:11 PM

Was This Post Helpful? 0
  • +
  • -

#9 Nakor  Icon User is offline

  • Professional Lurker
  • member icon

Reputation: 444
  • View blog
  • Posts: 1,492
  • Joined: 28-April 09

Re: Add dynamic controls & save contols values

Posted 21 August 2013 - 06:35 PM

The only way you're going to get it to work without usercontrols is to maintain a count of each individual control that gets added, especially if you are adding different controls for different events. I think you will have a lot easier time if you can at least group different sets of controls into UserControls.

This post has been edited by Nakor: 21 August 2013 - 06:35 PM

Was This Post Helpful? 0
  • +
  • -

#10 staindromeo  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 153
  • Joined: 21-October 10

Re: Add dynamic controls & save contols values

Posted 21 August 2013 - 07:49 PM

View PostNakor, on 21 August 2013 - 06:35 PM, said:

The only way you're going to get it to work without usercontrols is to maintain a count of each individual control that gets added, especially if you are adding different controls for different events. I think you will have a lot easier time if you can at least group different sets of controls into UserControls.


Hey Nakor,

Your code was flawless thanks, really put me in the right direction. Although I had to switch up the 'var' to 'control' because I am on .NET 2.0. I haven't been able to add the jquery datepicker to the textbox although I think I just need to work on it a little bit I may have missed something.

I did have a few questions though. Since everything is inside a div that is triggered to open & close based on a radiobutton which is working. I was just wondering if there is a way for the control to show up once the div opens instead of clicking on 'Add' to add the control. I am able to achieve this by adding a static Dropdownlist before loading the UserControl, but this may be redundant as I need to pass the values to a stored procedure so if I go with what I have currently then I'll have to combine the SelectedValues of the dropdownlist & the UserControl as one.

Which brings me to my second question. For the SelectedValues of the UserControl, how should I set it up for the stored procedure to be able to insert the selected values into the database. Previously I had done it this way:

DataIns.InsertData(Convert.ToInt32(Session["ID"]), place, "COMP>>COMP Near You?>>New Comp", NewCompetitors.SelectedValue.ToString(), NewCompetitorsOpenedDate.Text.ToString());


Do I just replace it with the IDs of the DropDownlist and the DatePicker textbox or do I need to specify the actual Control?

Thanks (Apologies for the Noobness :sweatdrop:/> )

This post has been edited by staindromeo: 21 August 2013 - 07:51 PM

Was This Post Helpful? 0
  • +
  • -

#11 staindromeo  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 153
  • Joined: 21-October 10

Re: Add dynamic controls & save contols values

Posted 22 August 2013 - 01:11 PM

Ok I tried looping through the placeholder to get the values of the controls so that I could pass it through the stored procedure. It didn't work as it's inserting blank values into the database for the 2 string values. Here's my code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
string DDLComp = "";
        string txtDate = "";
        foreach (Control ctrl in PlaceHolder1.Controls)
        {
            if (ctrl is DropDownList)
            {
                DropDownList ddl = (DropDownList)(ctrl);
                DDLComp += ddl.SelectedValue;

            }
            if (ctrl is TextBox)
            {
                TextBox txtbx = (TextBox)(ctrl);
                txtDate += txtbx.Text;
            }
       Data.InsertData(Convert.ToInt32(Session["ID"]), place, "COMP>>NewComp", DDLComp, txtDate;



Was This Post Helpful? 0
  • +
  • -

#12 staindromeo  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 153
  • Joined: 21-October 10

Re: Add dynamic controls & save contols values

Posted 22 August 2013 - 03:30 PM

Ok I figured how to get it to insert into the database, but it's only partly working. As it's only inserting the values from the last loaded controls. So if the control loads 3 times, it will only insert the value the user enters in the last dropdownlist and textbox. Did I miss something?

  protected void btnContinue_Click(object sender, EventArgs e)
    {

        string DDLComp = "";
        string txtDate = "";
        PlaceHolder ph =  (PlaceHolder)FindControl("PlaceHolder1");
        string test = "";
        if (NewComp.Checked)
        {
            for (int i = 0; i < ph.Controls.Count; i++)
            {
                test = ph.Controls[i].ID;
                Control cntrl = ph.FindControl(test);
                for (int k = 0; k < cntrl.Controls.Count; k++)
                {
                    if (cntrl.Controls[k].GetType() == typeof(DropDownList))
                    {
                        DropDownList ddl = (DropDownList)cntrl.Controls[k];
                        DDLComp = ddl.SelectedValue.ToString();
                    }
                    if (cntrl.Controls[k].GetType() == typeof(TextBox))
                    {
                        TextBox txtbx = (TextBox)cntrl.Controls[k];
                        txtDate = txtbx.Text;
                    }

                    
                    Data.InsertData(Convert.ToInt32(Session["ID"]), store, "COMP>>New Comp", DDLComp, txtDate);
                   

                }


Was This Post Helpful? 0
  • +
  • -

#13 Nakor  Icon User is offline

  • Professional Lurker
  • member icon

Reputation: 444
  • View blog
  • Posts: 1,492
  • Joined: 28-April 09

Re: Add dynamic controls & save contols values

Posted 23 August 2013 - 05:33 AM

I would create a property on the UserControl that returns the selected value of the dropdownlist control.

// in the .ascx.cs

// You can change the type of this, you
// will just need to cast the value in the return below
// to the same type
public string SelectedValue
{
    get
    {
        // Change this to the actual ID of the dropdownlist in the usercontrol
        return DropDownList1.SelectedValue;
    }
}




Then you can just loop through the usercontrols and grab the selectedvalue instead of trying to loop through all the controls in each usercontrol. You can basically do the same thing for each control that you need to get the value from.

Also, for the datepicker, did you notice in my .aspx code above that I have a section at the bottom where I am adding the datepicker to the control using Sys.Application.add_load?

This post has been edited by Nakor: 23 August 2013 - 05:31 AM

Was This Post Helpful? 0
  • +
  • -

#14 staindromeo  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 153
  • Joined: 21-October 10

Re: Add dynamic controls & save contols values

Posted 23 August 2013 - 11:28 AM

Thanks for the tip Nakor, although I'm running into another issue when trying to give the user an option to remove any added Usercontrol by clicking on an imagebutton which is in the usercontrol.

I get a NullReferenceException: object reference is not set to an instance of an object in the click event of the ascx.cs page.

.ascx
<asp:ImageButton runat="server" ID="btnDeleteComp" ImageUrl="~/images/Delete.png" onclick="btnRemove_Click"/>


.ascx.cs
public partial class Controls_AddComp : System.Web.UI.UserControl
{

public event EventHandler RemoveUserControl;

    protected void btnRemove_Click(object sender, System.EventArgs e)
    {
        
            RemoveUserControl(sender, e);
    }
}

If I add a if(RemoveUserControl !=null) to the above statement, then I don't get the NullReferenceExceptionerror but it doesn't delete the control either.

.cs file:
  public void HandleRemoveUserControl(object sender, EventArgs e)
    {
        Button Delbtn = sender as Button;
        UserControl DynamicUserControl = (UserControl)Delbtn.Parent;
        PlaceHolder1.Controls.Remove(DynamicUserControl);
    }


I did see the part for the Datepicker, the way I got it to work was by adding this to the usercontrol:
<script type="text/javascript">
$(function() {
    $( "#<%= txtDate.ClientID %>" ).datepicker();
});
</script>


Was This Post Helpful? 0
  • +
  • -

#15 Nakor  Icon User is offline

  • Professional Lurker
  • member icon

Reputation: 444
  • View blog
  • Posts: 1,492
  • Joined: 28-April 09

Re: Add dynamic controls & save contols values

Posted 23 August 2013 - 11:35 AM

instead of sending the sender object on from the button to the custom event try passing "this" so that sender is now a direct reference to the usercontrol.

public partial class Controls_AddComp : System.Web.UI.UserControl
{

public event EventHandler RemoveUserControl;

    protected void btnRemove_Click(object sender, System.EventArgs e)
    {
        
            RemoveUserControl(this, e);
    }
}


Then in the .cs

  public void HandleRemoveUserControl(object sender, EventArgs e)
  {
      UserControl DynamicUserControl = (UserControl)sender;
      PlaceHolder1.Controls.Remove(DynamicUserControl);
      ControlCount--;
  }

This post has been edited by Nakor: 23 August 2013 - 12:01 PM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2