Вопрос

I am trying to use the method described here to emulate an application page in a sandbox solution. The basic premise is to create a web part, and deploy a web part page that has that web part already embedded on it. You don't get the code-behind of the .aspx page, but you do get the server side code of the web part.

If I set up my markup like so

<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
    <WebPartPages:SPUserCodeWebPart
        <!-- all the stuff needed for the web part,
             like assembly name, solution id, etc. -->
        >
    </WebPartPages:SPUserCodeWebPart>
</asp:Content>

the web part loads fine, and I can add controls dynamically in the CreateChildControls() method. And I can add a button and a click handler:

myButton = new Button();
myButton.Text = "Submit";
myButton.Click += myButton_clickHandler;
this.Controls.Add(myButton);

However, when the page posts back, it seems that all the controls get lost, so there is no more button, and the click handler never fires.

On the other hand, if I set up my markup like this:

<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
    <WebPartPages:SPUserCodeWebPart
        <!-- all the stuff needed for the web part,
             like assembly name, solution id, etc. -->
        >
    </WebPartPages:SPUserCodeWebPart>
    <asp:TextBox ID="textBox" runat="server"></asp:TextBox>
    <asp:Button ID="myButton" runat="server" Text="Submit"></asp:Button>
</asp:Content>

then I can't seem to get to the other controls from within the web part's server side code. I've tried looking at this.Page.Controls and this.Parent.Parent etc., but those other controls aren't there.

So what am I missing? How can I get this set up to work, where I can have some controls on the page (dynamically added during CreateChildControls() is fine), and reliably access them to get values and fire event handlers on post-back?

Это было полезно?

Решение

During post back you need to recreate controls and attach event as

if(IsPostBack){
    CreateDynamicControlsEvents();
}


void CreateDynamicControlsEvents() {
    myButton = new Button();
    myButton.Text = "Submit";
    myButton.Click += myButton_clickHandler;
    this.Controls.Add(myButton);
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с sharepoint.stackexchange
scroll top