How to update label from callback function in code behind?

1.3k Views Asked by At

My ASP.NET project calls a REST-Client library function, which callback should adjust the label. But the asp label won't change or update after callback is called. Is it possible over callback?

Default.aspx:

<asp:UpdatePanel runat="server" id="UpdatePanel1">
    <ContentTemplate>
        <asp:Button OnClick="connect" Text="Connect" runat="server" />
        <asp:Label runat="server" Text="Label to be changed" id="Label1">
        </asp:Label>
    </ContentTemplate>
</asp:UpdatePanel>

Default.aspx.cs:

public void connect(object sender, EventArgs e)
{
    Program restCLient = new Program();
    restCLient.startConnection(writeToConsole);
}

public void writeToConsole(string str)
{
    Label1.Text = str;
}

Programm.cs:

public void startConnection(Action<string> callbackLog)
{
    callbackLog("result");
}
1

There are 1 best solutions below

5
On BEST ANSWER

Label1 is not referenced in startConnection, it will have a new instance. Best way to do this is to return a string from startConnection and change the label in connect() method.

One workaround is to send the calling page instance as a parameter to the startConnection method and call the method on that parameter. Assuming your page class is called Default and Programm.cs is in the same application you can use something like this:

public void startConnection(ref Default callingPage)
{
    callingPage.writeToConsole("result");
}

Then you would call the method like this:

restCLient.startConnection(this);