Timer in ASP.NET webform to update a label text - asp.net

I use this code for create timer that want to update a label each second:
timer = new System.Timers.Timer();
timer.Elapsed += new ElapsedEventHandler(OnRefresh_Tick);
timer.Interval = 1000;
The function OnRefresh_Tick call each second but the label text doesn't change.
Edit:
I use the below code for the timer, but when the timer starts, I can't write in the second textbox (txtPassword) and it refreshes and the cursor goes to the first textbox (txtUserName)
.aspx file:
<form id="form1" runat="server">
<br /><br />
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtUserName" runat="server" Height="30px" Width="100px"></asp:TextBox><br /><br />
<asp:TextBox ID="txtPassword" runat="server" Height="30px" Width="100px"></asp:TextBox><br /><br />
<asp:Label runat="server" id="lnkSendVerificationCode"></asp:Label><br /><br />
<asp:Button ID="Button1" runat="server" Text="Start Timer" CssClass="btn" OnClick="Button1_Click"/>
<asp:Timer ID="Timer1" runat="server" Enabled="False" Interval="1000" OnTick="Timer1_Tick"></asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
</form>
.cs file:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
}
}
protected void Button1_Click(object sender,EventArgs e)
{
Session["VerificationCodeCounter"] = "20";
Timer1.Enabled = true;
}//Button1_Click
protected void Timer1_Tick(object sender, EventArgs e)
{
int sendVerificationCounter = -1;
try { sendVerificationCounter = int.Parse(Session["VerificationCodeCounter"].ToString()); } catch { }//catch
if (sendVerificationCounter == 1)
{
sendVerificationCounter = -1;
Session["VerificationCodeCounter"] = sendVerificationCounter.ToString();
Timer1.Enabled = false;
}//if
else if (sendVerificationCounter > 0)
{
sendVerificationCounter--;
lnkSendVerificationCode.Text = sendVerificationCounter.ToString();
Session["VerificationCodeCounter"] = sendVerificationCounter.ToString();
}//else if
}//Button1_Click

Try say this:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div style="padding:25px">
<h4>enter seconds to count down</h4>
<asp:TextBox ID="txtCount" runat="server"
Height="42px"
Width="80px"
Font-Size="XX-Large"
Text="0"
style="text-align: center">
</asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Start Timer" CssClass="btn" OnClick="Button1_Click"/>
<asp:Timer ID="Timer1" runat="server" Enabled="False" Interval="1000" OnTick="Timer1_Tick"></asp:Timer>
<br />
</div>
And code behind would be this:
protected void Button1_Click(object sender, EventArgs e)
{
Timer1.Interval = 1000; // tick our timer each second
Timer1.Enabled = true;
}
protected void Timer1_Tick(object sender, EventArgs e)
{
int MyCount = Convert.ToInt32(txtCount.Text);
if (MyCount > 0 )
{
MyCount = MyCount - 1;
txtCount.Text = MyCount.ToString();
}
else
{
// we are done, stop the timer
Timer1.Enabled = false;
}
}
So, we now see this if we enter 10 (for 10 seconds).
If we hit start timer, then it counts down to 0, and then stops the timer.
Edit: With a up-date panel
So, if we don't want a whole page re-fresh, then we can use this:
<h4>enter seconds to count down</h4>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtCount" runat="server"
Height="42px"
Width="80px"
Font-Size="XX-Large"
Text="0"
style="text-align: center">
</asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Start Timer" CssClass="btn" OnClick="Button1_Click"/>
<asp:Timer ID="Timer1" runat="server" Enabled="False" Interval="1000" OnTick="Timer1_Tick"></asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
Remember, while the whole page will now not re-fresh, do keep in mind that the page life cycle DOES trigger. So, if you have some code in on-page load to setup controls? Then you need this
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// code here to load up grids, and controls
// code here ONLY runs on first time page load
}
}
So, keep in mind that for any up-date panel (button clicks, timer etc.), then the page load event DOES fire each time.
However, that !IsPostback check? The last 100+ web pages I created that loads or sets up ANYTHING on a page will have the above code stub, and check for !IsPostback.
You can't quite even make a working webforms page unless you follow the above rule. What this means is your page can now handle post-backs, and not re-load controls and run the first time setup of such controls.
So, keep in mind, a update panel DOES post-back, and does trigger the page load event. Better said, a update panel, and click of a button (or timer) inside will post-back, but it what we call a partial page post-back.
Edit3: With a label
So, say we want a label - not a text box. Then do this:
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div style="padding:25px">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="txtCount" runat="server"
Height="42px"
Width="80px"
Font-Size="XX-Large"
Text="999"
style="text-align: center">
</asp:Label>
<br />
<asp:Button ID="Button1" runat="server" Text="Start Timer" CssClass="btn" OnClick="Button1_Click"/>
<asp:Timer ID="Timer1" runat="server" Enabled="False" Interval="1000" OnTick="Timer1_Tick"></asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
<br />
</div>
</form>
</body>
And now our code becomes this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// code here to load up grids, and controls
// code here ONLY runs on first time page load
txtCount.Text = "10";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Timer1.Interval = 1000; // tick our timer each second
Timer1.Enabled = true;
}
protected void Timer1_Tick(object sender, EventArgs e)
{
int MyCount = Convert.ToInt32(txtCount.Text);
if (MyCount > 0 )
{
MyCount = MyCount - 1;
txtCount.Text = MyCount.ToString();
}
else
{
// we are done, stop the timer
Timer1.Enabled = false;
}
}
And now we see this:

Related

how to create 2 minute countdown timer using asp.net

i want to create a 2 minute timer under text box using Asp.net, i wanted the timer to be in a label under the text box, so i wrote this code in the control page after double click in the timer icon:
int seconds = int.Parse(Label1.Text);
if (seconds > 0)
Label1.Text = (seconds - 1).ToString("mm:ss");
else
Timer1.Enabled = false;
And this code in the aspx file:
<span "CodeAsk">ألم تتلقى الرمز ؟</span><asp:Label ID="Label1" runat="server" text="2"></asp:Label>
<asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick" Interval="120000"></asp:Timer>
but it's not working, what is the problem with my code?
but it's not working, what is the problem with my code?
Timer needs to be used in conjunction with the UpdatePanel control. You can trigger the ontick event of the timer through the AsyncPostBackTrigger method of the updatepanel.
And for converting the text of the Label into the form of a timer, you need to use TimeSpan time = TimeSpan.FromSeconds(seconds); to achieve, you can refer to this.
<form runat="server">
<asp:ScriptManager runat="server" ID="ScriptManager1" />
<asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick" Interval="1000">
</asp:Timer>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<span id="CodeAsk">ألم تتلقى الرمز ؟</span><br />
<asp:Label ID="Label1" runat="server" Text="2"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
</form>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
TimeSpan time = TimeSpan.FromSeconds(Convert.ToInt32(Label1.Text) * 60);
string str = time.ToString(#"hh\:mm\:ss");
Label1.Text = str;
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
TimeSpan result = TimeSpan.FromSeconds(TimeSpan.Parse(Label1.Text).TotalSeconds - 1);
string fromTimeString = result.ToString(#"hh\:mm\:ss");
Label1.Text = fromTimeString;
}
Here is the test result:

How to display records with time interval

I have a website i.e. I'm working on aspx pages. I am storing value in to the xml file.
I need to display value stored in xml at specified time interval (say 1 min) on a asp label. But not all records are to display at an instance. At first instance first record of xml and after time interval next record and so on. After last record again first record needed to display.
I Google search a lot on this but could not find specific solution on this.
Please help me with successful solution. Thanks...
This is my code but its not giving expected results. Please help me in editing this.
HTML code
<div>
<table width="100%">
<tr><td>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
</td></tr>
<tr><td>
<asp:Timer ID="Timer1" runat="server" ontick="Timer1_Tick">
</asp:Timer>
</td></tr>
<tr><td>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="" ></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="timer1" EventName ="tick" />
</Triggers>
</asp:UpdatePanel>
</td></tr>
<tr><td></td></tr>
</table>
</div>
ASPX coding
public partial class UpdateNews : System.Web.UI.Page
{
DataRow dr;
int i = 1;
protected void Page_Load(object sender, EventArgs e)
{
if (!ScriptManager1.IsInAsyncPostBack)
Session["timeout"] = DateTime.Now.AddMinutes(120).ToString();
//GetNewValue();
}
protected void Timer1_Tick(object sender, EventArgs e)
{
if (0 > DateTime.Compare(DateTime.Now,
DateTime.Parse(Session["timeout"].ToString())))
{
i++;
GetNewValue();
}
}
public void GetNewValue()
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("News.xml"));
DataTable dt = ds.Tables[0];
if (i <= dt.Rows.Count)
{
dr = dt.Rows[i - 1];
Label1.Text = dr["Title"].ToString();
}
else
{
if(i > dt.Rows.Count )
i = 1;
}
}
}
You can use time with update panel in asp.net web forms.
Following is the code :
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
<ContentTemplate>
<!-- your content here, no timer -->
</ContentTemplate>
Things you want to do can be put in timer1_tick
I got the answer now my code is running properly.
But now When I put my page in content page I get an new error :-(
Please help me I need to clear this error at its earliest due to my deadline.
It say: cannot implicitly convert type 'string' to 'system.web.ui.webcontrols.label' at line 1
Where line 1 is
<%# Page Language="C#" MasterPageFile="~/Main.master" AutoEventWireup="true" CodeFile="Home.aspx.cs" Inherits="Home" Title="Untitled Page" %>
My working code is here :
HTML Code
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Timer ID="Timer1" runat="server" ontick="Timer1_Tick">
</asp:Timer>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Title" runat="server" Text=""></asp:Label>
<asp:Label ID="News" runat="server" Text=""></asp:Label>
<asp:Label ID="Counter" runat="server" Text="" ></asp:Label>
</ContentTemplate>
<Triggers><asp:AsyncPostBackTrigger ControlID="timer1" EventName ="tick" /></Triggers>
</asp:UpdatePanel>
ASPX Code:
public partial class Home : System.Web.UI.Page
{
DataRow dr;
int i = 1;
protected void Page_Load(object sender, EventArgs e)
{
if (!ScriptManager1.IsInAsyncPostBack)
Session["timeout"] = DateTime.Now.AddMinutes(100).ToString();
if (!string.IsNullOrEmpty(Counter.Text))
{
i = int.Parse(Counter.Text);
i++;
}
GetNewValue();
}
public void GetNewValue()
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("News.xml"));
DataTable dt = ds.Tables[0];
if (i <= dt.Rows.Count)
{
dr = dt.Rows[i - 1];
Title.Text = dr["Title"].ToString();
News.Text = dr["Description"].ToString();
Counter.Text = i.ToString();
}
else
{
if (i > dt.Rows.Count)
i = 1;
Counter.Text = i.ToString();
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
if (0 > DateTime.Compare(DateTime.Now,
DateTime.Parse(Session["timeout"].ToString())))
{
GetNewValue();
}
}
}
My code was correct
Just error was I should not rename ID field of Labels in update panel.
I dont know why this happened.
But when I renamed my Title, counter,News label to label1 label2....
It worked properly and gave me my required result.
Thank you all for responding and trying to help me.

programmatically added click event in user control won't fire

I'm having issues getting the click event for a button contained within a programmatically added user control to fire. I understand that the event must be wired up each time a new user control is added, and I'm pretty sure I'm doing that, but still nothing. The click event for the button works fine for the first user control, which is not added programmatically. Here's the markup for the user control....
<asp:Panel ID="pnlAddressForm" runat="server">
<asp:Label ID="lblStreet" runat="server" Text="Street Address"></asp:Label>
<asp:TextBox ID="txtStreet" runat="server"></asp:TextBox>
<br /><br />
<asp:Label ID="lblCity" runat="server" Text="City"></asp:Label>
<asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
<br /><br />
<asp:Label ID="lblState" runat="server" Text="State"></asp:Label>
<asp:TextBox ID="txtState" runat="server"></asp:TextBox>
<br /><br />
<asp:Label ID="lblZip" runat="server" Text="Zip"></asp:Label>
<asp:TextBox ID="txtZip" runat="server"></asp:TextBox>
<br /><br />
<asp:Button ID="btnRemoveAddress" runat="server" Text="Remove Address" OnClick="btnRemoveAddress_Click" />
</asp:Panel>
...and here's the markup for the main page...
<form id="form1" runat="server">
<div>
<My:FormUserControl runat="server" ID="myFormUserControl" />
<br /><br />
<hr />
<My:AddressUserControl runat="server" ID="myAddressUserControl" />
<br /><br />
<asp:PlaceHolder ID="phAddresses" runat="server"></asp:PlaceHolder>
<br /><br />
<asp:Button ID="btnAddAddress" runat="server" Text="Add Another Address" OnClick="btnAddAddress_Click" />
</div>
<br /><br />
<hr />
<asp:Button ID="btnSubmit" runat="server" Text="Create PDF" OnClick="btnSubmit_Click" />
</form>
..as you can see it already contains one AddressUserControl declaratively. All subsequent AddressUserControls are added to phAddresses once btnAddAddress is clicked. AddressUserControls are added this way in the code behind...
private static List<AddressUserControl> addresses = new List<AddressUserControl>();
protected void Page_PreInit(object sender, EventArgs e)
{
int addressCount = 0;
foreach (AddressUserControl aCntrl in addresses)
{
Literal ltlSpace = new Literal();
ltlSpace.Text = "<br /><br />";
phAddresses.Controls.Add(aCntrl);
phAddresses.Controls.Add(ltlSpace);
addressCount++;
}
}
When btnAddAddress is click this event handler runs...
protected void btnAddAddress_Click(object sender, EventArgs e)
{
AddressUserControl aCntrl = LoadControl("~/UserControls/AddressUserControl.ascx") as AddressUserControl;
findAddressControlRemoveButton(aCntrl);
addressUserControlButton.ID = "btnRemoveAddress" + addresses.Count + 1;
addressUserControlButton.Click += new EventHandler(addressUserControlButton_Click);
addresses.Add(aCntrl);
}
...and here's the addressUserControlButton event handler. This never runs, I suppose I'm not adding it correctly in the above handler?
private void addressUserControlButton_Click(object sender, EventArgs e)
{
Button thisButton = sender as Button;
thisButton.Text = "Why Hello";
}
EDIT - Ok, so I moved the eventhandler assignment to Page_PreInit instead of within btnAddAddress_Click, like so....
protected void Page_PreInit(object sender, EventArgs e)
{
int addressCount = 0;
foreach (AddressUserControl aCntrl in addresses)
{
Literal ltlSpace = new Literal();
ltlSpace.Text = "<br /><br />";
phAddresses.Controls.Add(aCntrl);
findAddressControlRemoveButton(aCntrl);
addressUserControlButton.ID = "btnRemoveAddress" + addressCount;
addressUserControlButton.Click += new EventHandler(addressUserControlButton_Click);
phAddresses.Controls.Add(ltlSpace);
addressCount++;
}
}
Not totally clear on why or how this fixed the problem though.
When you add any control programmatically, you need to register click event after that.

UpdatePanel not refreshing

I'm a newbie with ASP.NET, so probably my question is easy... but I'm wasting a lot of time with no success.
Part of my page is
<asp:UpdatePanel ID="pnlFileUpload" runat="server">
<ContentTemplate>
<ajaxToolkit:AsyncFileUpload ID="upload" runat="server" OnUploadedComplete="upload_UploadedComplete"
OnUploadedFileError="upload_UploadedFileError" UploaderStyle="Modern" UploadingBackColor="Yellow"
Width="400px" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="pnlFileError" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblFileError" runat="server" Text="errFile" Visible="false"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="upload" EventName="UploadedComplete" />
</Triggers>
</asp:UpdatePanel>
When user uploads (started with ajaxToolkit:AsyncFileUpload) ends, upload_UploadedComplete is called.
A sample code is:
protected void upload_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
int size = upload.PostedFile.ContentLength;
if (size > maxsize)
{
lblFileError.Text = 'File too big...';
lblFileError.ForeColor = System.Drawing.Color.Red;
lblFileError.Visible = true;
pnlFileError.Update();
}
}
But lblFileError is never shown... why?!?
AsyncFileupload doesn't need updatePanel ( none of AJAx toolkit controls need ) . as they have it as a built in . remove fileupload UpdatePanel and test again
:
it seems you can't do that in this way . based on AjaxControlToolkitSampleSite to show user a message about uploading file you should use "ScriptManager.RegisterClientScriptBlock" as below :
protected void upload_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
int size = upload.PostedFile.ContentLength;
if (size > maxsize)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "error", "top.$get(\"" + lblFileError.ClientID + "\").innerHTML = 'File too big...';", true);
}
}

UpdatePanel with ASP.NET Repeater and Checkbox Aync Postback issue

I have a rather annoying issue here
I can't get my CheckBox CheckedChange event to fire, or catch or whatever it is that fails:
ASPX Code
<asp:UpdatePanel runat="server" ID="udp_Lists" UpdateMode="Always">
<ContentTemplate>
<asp:Repeater ID="rep_showings" runat="server">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<div class="div_assignment">
<div class="div_assignment_text">
<asp:LinkButton runat="server" ID="lnk_show_task" OnClick="lnk_show_task_Click" CommandArgument='<%# Eval("Id") %>' Text='<%# Eval("TaskTitle") %>'></asp:LinkButton>
</div>
<div class="div_assignment_checkbox">
<asp:CheckBox runat="server" ID="chk_handle" AutoPostBack="true" OnCheckedChanged="chk_handle_Changed" ToolTip='<%# Eval("Id") %>' />
</div>
</div>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
</ContentTemplate>
<Triggers>
</Triggers>
The Code behind function "chk_handle_Changed" is never reached.
The Linkbutten works perfectly.
I took a look at your problem. I used the following code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.rep_showings.DataSource = new object[] { new { Title = "title", ID = "id" } };
this.rep_showings.DataBind();
}
}
protected void chk_handle_Changed(object source, EventArgs e)
{
Trace.Write("here");
}
protected void lnk_show_task_Click(object source, EventArgs e)
{
Trace.Write("here 2");
}
protected void rep_showings_ItemCommand(object source, RepeaterCommandEventArgs e)
{ }
The above code works. I think you are probably re-binding your repeater on every postback - I tested this by removing the "if (!IsPostBack)" statement in Page_Load(), and I was able to reproduce the problematic behaviour you describe.
Rebinding a control on every postback should be avoided if possible. Once a control is populated, it's data is taken care of by ViewState, so unless the data is changing, you should probably not be rebinding it all the time.

Resources