SharePoint 2010: Retaining the values of Dynamically created Textboxes in a Sandboxed Visual WebPart

If you instantiating your controls such as texboxes, on the runtime in a web part, chances are high that you would lose the values once a postback occurs. To retain the values in the text boxes, we ought to recreate them on every postback and get the values from the Form collection. In addition to the that the use of the ViewState variable is also helpful. So here goes my code:

So suppose you have two buttons

  • CreateTextbox Button: Create a new textbox for you 
  • Save button: Searches for the text boxes and saves the value in the text boxes if any.

    
 private void Page_Load(object sender, System.EventArgs e)
    {
        if(Page.IsPostBack)
            ViewState["NumberOfTextboxes"] = 0;                
        else
            this.createControls();
    }

 private void createTextboxes()
    {
        for(int i = 0; i < count; i++)
        {
            TextBox tbx = new TextBox();
            tbx.ID = "tbx" + i.ToString();
            Page.Controls.Add(tbx);
        }
    }

  private void addTextbox()
    {        
      NumberOftextboxes = (int)ViewState["NumberOfTextboxes"];
      TextBox tbx = new TextBox();
      tbx.ID = "tbx" + NumberOftextboxes.ToString();
      Page.Controls.Add(tbx);
      NumberOfTextboxes++;
      ViewState["NumberOfTextboxes"] = NumberOfTextboxes;
     }

   
  void saveButton_Click(Object sender, CommandEventArgs e)
  {
   Control control = null;
   int i = 0;
   foreach (Control ctrl in Page.Controls)
    {
     control = Page.FindControl("tbx"+i);
     if (control!= null)       
      SaveValue(Control);
     i++;           
    }
  void CreateControl_Click(Object sender, CommandEventArgs e)
  { 
   addTexbox();
  }
 
  void SaveValue(Control ctrl)
  {
   //Write code to save the value where you would like to.
  }

Hope this helps Cheers
Vaqar Hyder

E: vaqar.hyder3567@gmail.com

A:

Siebenbürgen Straße 2/1, Korntal-Münchingen, 70825, PK

Hire me on Freelancer.com

Comments

Popular posts from this blog

SPFx: Develop using SharePoint Framework without Installing all the dependecies.

SharePoint Online: Elevated Permissions....with love

Powershell: Filling up an Existing Excel Sheet with data from SQL Server