0

I have a Placeholder where a table is dynamically added on page load (everything loads fine and I can see control[0] when debugging without a problem. When button is clicked to reset the form, I try to access that table at control[0] and get "index out of range". I have researched quite a bit and can not find why that is happening.

Here is the code when page loads:

    private void LoadTable()
    {
        Table oTable = new Table();

        //gather table row and cell info here - table loads fine on page

        PlaceHolder1.Controls.Add(oTable);
    }

This code fires when button is clicked:

    private void ResetForm()
    {
        //clear out textboxes and dropdown lists

        Table oTable = new Table();
        oTable = (Table)PlaceHolder1.Controls[0];  // this is where problem occurs
    }

and the HTML:

<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

I hope that it isn't something obvious that I'm missing, since I'm still fairly new to programming. Any help is appreciated!

deebs
  • 1,390
  • 10
  • 23
  • 1
    Do you have a `IsPostBack` control for `LoadTable()`method in `PageLoad` event? – Uğur Aldanmaz Mar 27 '15 at 19:37
  • Where are you calling ResetForm()? – Kami Mar 27 '15 at 19:46
  • Actually that LoadTable() method was in if (!Page.IsPostBack)... I moved it out and that did the trick. Thank you! Can you explain further why the PlaceHolder1 loses its data on PostBack? I'll accept your answer if you provide one. – deebs Mar 27 '15 at 19:46
  • @Kami on button_Click – deebs Mar 27 '15 at 19:46
  • On Postback the aspx page re-renders and all controls are reset. if you want to keep the data in your place holder put it in an Ajax UpdatePanel. – Kami Mar 27 '15 at 19:52
  • I am confused. You did call the LoadTable method in if(!IsPostBack) but you moved out and problem solved. Actually I would say that put it in the IsPostBack control. – Uğur Aldanmaz Mar 27 '15 at 20:13
  • Correct - I guess it was losing its data with the PostBack, and the Placeholder didn't reload the table. It is firing on IsPostBack now (the LoadTable method), so everything is working. – deebs Mar 27 '15 at 20:20

0 Answers0