Reputation: 47
I want to create a user control that represents a progress bar.
ASCX:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ProgressBar.ascx.cs" Inherits="A2Controls.Controls.ProgressBar" %>
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="<%# this.Value %>" aria-valuemin="0" aria-valuemax="100" style="width: <%# this.Value %>%">
<span class="sr-only"><%# this.Value %> Complete</span>
</div>
</div>
Code Behind:
public partial class ProgressBar : System.Web.UI.UserControl
{
public int Value { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
}
}
ASPX:
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Timer runat="server" ID="clock" OnTick="clock_Tick" Interval="1000" Enabled="true"></asp:Timer>
<uc1:ProgressBar runat="server" ID="ProgressBar" />
</ContentTemplate>
<Triggers >
<asp:AsyncPostBackTrigger ControlID="clock" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
Code Behind:
protected void clock_Tick(object sender, EventArgs e)
{
this.ProgressBar.Value++;
}
The problem is that every time the tick function is called, the updatepanel refreh and reload the whole usercontrol (calling the constructor I mean)! I've tried to put the updatepanel logic inside the usercontrol but there is no difference.
How can I prevent the usercontrol re-instantiate again?
Upvotes: 2
Views: 793
Reputation: 5259
You have to change your Value
property to this:
public int Value
{
get
{
if (ViewState["Value"] != null)
return (int)ViewState["Value"];
else
return 0;
}
set
{
ViewState["Value"] = value;
}
}
In this way you keep the property's value across postbacks.
HTTP
is a stateless protocol. Unfortunately you have to use some kind of trick to persist data across requests like the ViewState
does. You better have a look here and here to deeply understand that there's nothing wrong here.
Upvotes: 1