views:

444

answers:

1

I write an imagebutton to a table cell in a new row when a user selects an item in a list:

ImageButton imgbtnRemove = new ImageButton();
imgbtnRemove.ID = "uxStandardLetterDeleteImage_" + items.letterName;
imgbtnRemove.CommandName = "uxStandardLetterDeleteImage_" + items.letterName;
imgbtnRemove.ImageUrl = items.remove;
imgStatus.AlternateText = "Remove";
tRow.Cells[3].Controls.Add(imgbtnRemove);

When the new imagebutton is clicked, I can't seem to get a handle to it. I see it in Page_PreRender event, where I also reload the table on each postback.

string returnData = Request.Form.ToString();

but iterating through the form controls images:

if (c is System.Web.UI.WebControls.Button ||
c is System.Web.UI.WebControls.ImageButton)

does not find it. I can find it if I manually put in a:

imgbtnRemove.Click += new System.Web.UI.ImageClickEventHandler(this.ButtonClick);

in the Page_Load and then grab it in the click event:

switch (((System.Web.UI.WebControls.ImageButton)sender).CommandName)
...

but because there are new rows being added and deleted, this gets rather ugly programmatically. I'm thinking there must be an elegant solution to dynamic imagebutton creation and retrieval on the fly from server side code. I've done a lot of digging but this one is stumping me.

Thanks in advance...

+2  A: 

If you're creating dynamic controls during the event handling phase of the Page lifecycle (for example, in the item selected event), then the control will be gone on the next postback.

In order for dynamic controls to be registered with ViewState, they have to be created in the Init phase of the event lifecycle.

Also, you say you're iterating through the Form's controls... when you are adding the imagebutton to the table's cells. Are you recursively descending the control heirarchy to look for the imagebutton?

womp
Moving the table recreation to OnInit allowed me to find the control in my (recursive) control method but I lost the new row add once the panel loaded...but I think I can work it out. Thanks!
32U