I need to generate buttons initially based on quite a processor and disk intensive search. Each button will represent a selection and trigger a postback. My issue is that the postback does not trigger the command b_Command. I guess because the original buttons have not been re-created. I cannot affort to execute the original search in the postback to re-create the buttons so I would like to generate the required button from the postback info.
How and where shoud I be doing this? Should I be doing it before Page_Load for example? How can I re-construct the CommandEventHandler from the postback – if at all?
namespace CloudNavigation { public partial class Test : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) { // how can I re-generate the button and hook up the event here // without executing heavy search 1 } else { // Execute heavy search 1 to generate buttons Button b = new Button(); b.Text = 'Selection 1'; b.Command += new CommandEventHandler(b_Command); Panel1.Controls.Add(b); } } void b_Command(object sender, CommandEventArgs e) { // Execute heavy search 2 to generate new buttons Button b2 = new Button(); b2.Text = 'Selection 2'; b2.Command += new CommandEventHandler(b_Command); Panel1.Controls.Add(b2); } } }
The b_Command Event Handler method is not being executed because on post back buttons are not being recreated (since they are dynamically generated). You need to re-create them every time your page gets recreated but in order to do this you need to explicitly cache information somewhere in state.
If this a page-scoped operation easiest way is to store it in the ViewState (as strings – if you start loading the ViewState with objects you’ll see performance go down) so that you can check it on next load (or any other previous event) and re-create buttons when reloading the page. If the operation is session-scoped, you can easily store an object (array or whatever) in session and retrieve it on next Load (or Init) to re-create your controls.
This scenario means that you need just to store some info about your button in your b_Command EventHandler instead of creating and adding buttons since if you do so you’ll lose relative information in the next postback (as it is happening now).
so your code would become something like:
If you don’t want to call recreateButtons on page load you can do it on PreLoad or on Init events, I don’t see a difference since you’ll be able to access ViewState/Session variables everywhere (on Init viewstate is not applied but you can access it to re-create your dynamic buttons).
Someone will hate this solution but as far as I know the only way to retain state data server-side is ViewState – Session – Page.Transfer or client-side cookies.