0

I am adding the dynamically TextBox in the placeholder on the button click in that.

When all the textboxes are loaded I am making changes in the values and again Press another Button to save the values to the SharePoint List. But when I press the Save button and I checked the placeholder by debugging it I found that there were no any control in the placeholder.
I am adding the Controls like follows :

TextBox[] tb = new TextBox[item_ans.Count];
Literal[] lt = new Literal[item_ans.Count];
for (int j = 0; j < item_ans.Count; j++)
{
   ans_id.Add(item_ans[j]["ID"].ToString());
   tb[j] = new TextBox();
   tb[j].ID = "tb_ans" + (j + 1).ToString();
   tb[j].Text = item_ans[j]["Title"].ToString();
   lt[j] = new Literal();
   lt[j].Text = "<br/>";
   pl_hd_ans.Controls.Add(tb[j]);
   pl_hd_ans.Controls.Add(lt[j]);
}

And on the Save Button click I am Retrieving those TextBoxes Like follows:

int n = Convert.ToInt32(ViewState["totalAns"].ToString());

foreach (var i in ans_id)
{
    var item_ans = list_ans.GetItemById(i);
    clientContext.Load(item_ans);
    clientContext.ExecuteQuery();

    for (int k = 0; k < n; k++)
    {
       TextBox tb = (TextBox)pl_hd_ans.FindControl("tb_ans" + (k + 1).ToString());
       item_ans["Title"] = tb.Text;
       item_ans.Update();
       clientContext.Load(item_ans);
       clientContext.ExecuteQuery();
    }                
}

But in this I check the Placeholder's Controls that were 0. Can Any one please help me to solve this..?

Rahul Gokani
  • 1,688
  • 5
  • 25
  • 43
  • 1
    TextBox[] tb = new TextBox[item_ans.Count]; tb should NOT be a local variable, it should be a class member or property? Otherwise tb is lost when it is out of scope of the function? – David May 27 '13 at 05:20
  • Hey Stil am not getting controls. Again the controls are 0 in placeholder... – Rahul Gokani May 27 '13 at 05:30
  • I just put the `TextBox[] tb;` out side the class as global variable. and then initialize it by giving the value to the array as I have mentioned on my question. – Rahul Gokani May 27 '13 at 05:33

1 Answers1

3

I'm assuming its ASP.NET WebForms what we're talking about here.

When you are adding controls dynamically to the webpage, you have to recreate them on each sequential postback. The reason for this, is that the dynamically created controls are not present in the .aspx file, nor in the viewstate, so asp.net cannot know that it has to recreate these controls. Therefore, you yourself have to recreate them in the initialized-event (before the page-load), including adding any event handlers that you need.

You can google about it.

Maarten
  • 22,527
  • 3
  • 47
  • 68