I am developing an web application where i need a count down timer. Im using asp.net
asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="lblHour" Text="" runat="server"></asp:Label>
<asp:Label ID="lblMin" Text="" runat="server"></asp:Label>
<asp:Label ID="lblSec" Text="" runat="server"></asp:Label>
<asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="timer_Tick">
</asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
Code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["time"] = DateTime.Now.AddSeconds(40);
}
}
protected void timer_Tick(object sender, EventArgs e)
{
TimeSpan time1 = new TimeSpan();
time1 = (DateTime)Session["time"] - DateTime.Now;
if (time1.Seconds <= 0)
{
lblSec.Text = "TimeOut!";
}
else
{
lblSec.Text = time1.Seconds.ToString();
}
}
The problem i am having is, the timer wont decrement properly. It starts with 38, then goes to 35 then 32 and so on.
Is there a way to fix this problem?
I reckon the issue here is that when timer is triggered, the time it executes the code, it is little longer then one sec, 1 sec + some micro seconds, this is the cause of this output. Test this in your code.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["time"] = DateTime.Now.AddSeconds(40);
}
}
protected void timer_Tick(object sender, EventArgs e)
{
var endTime = (DateTime) Session["time"];
var endMin = ((DateTime)Session["time"]).Minute;
var endSec = ((DateTime)Session["time"]).Second;
var endMsec = ((DateTime)Session["time"]).Millisecond;
var currentTime = DateTime.Now;
var currentMin = currentTime.Minute;
var currentSec = currentTime.Second;
var currentMsec = currentTime.Millisecond;
var time1 = endTime - currentTime;
lblHour.Text = string.Format("End Sec - {0}:{1}:{2}", endMin, endSec, endMsec);
lblMin.Text = string.Format("Current Sec - {0}:{1}:{2}", currentMin, currentSec, currentMsec);
lblSec.Text = time1.Seconds <= 0 ? "TimeOut!" : time1.Seconds.ToString();
}
Related
My application consists of a web form that someone may be pulling some information in. When that occurs, I'm loading a user control more than once, based on content, that has an ImageButton on it.
Since this is being loaded after page is already loaded, how can I get the click events to work properly. Since click events are required to be set during page_load.
Example Scenario:
Main.aspx
<form id="form1" runat="server">
<div>
<asp:Button ID="clicker" runat="server" Text="Click Me" />
<asp:PlaceHolder ID="PHwfuc" runat="server"></asp:PlaceHolder>
<asp:Label runat="server" ID="ResponseMessage"></asp:Label>
</div>
</form>
Main.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
clicker.Click += new EventHandler(this.ButClick);
}
protected void ButClick(object sender, EventArgs e)
{
PlaceHolder placeHolder = new PlaceHolder();
for (int i = 0; i < 2; i++)
{
WFUC1 test = LoadControl("~/WebFormUserControl/WFUC1.ascx") as WFUC1;
test.Ident = i;
placeHolder.Controls.Add(test);
}
PHwfuc.Controls.Add(placeHolder);
}
WFUC1.ascx
<asp:PlaceHolder runat="server" ID="DelAddrBtn"></asp:PlaceHolder>
<asp:Label runat="server" ID="ResponseMessage"></asp:Label>
<br />
WFUC1.ascx.cs
public WFUC1()
{
TrashIcon = new ImageButton
{
AlternateText = "Delete Address",
ImageUrl = "/images/trash.png",
ToolTip = "Delete Address",
};
TrashIcon.Style.Add("cursor", "pointer");
TrashIcon.Style.Add("width", "24px");
}
private ImageButton TrashIcon { get; set; }
public int Ident { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
TrashIcon.ID = $"Delete_{Ident}";
TrashIcon.Click += new ImageClickEventHandler(this.TrashIcon_Click);
DelAddrBtn.Controls.Add(TrashIcon);
}
protected void TrashIcon_Click(object sender, ImageClickEventArgs e)
{
ResponseMessage.Text = $"Use Control Got it. {Ident}";
}
EDIT For Rango
WFUC1.ascx
<asp:ImageButton runat="server" ID="TrashIcon" ImageUrl = "/images/trash.png" ToolTip = "Delete Address" OnClick="TrashIcon_Click" />
<asp:Label runat="server" ID="ResponseMessage"></asp:Label>
<br />
WFUC1.ascx.cs
public partial class WFUC1 : System.Web.UI.UserControl
{
public int Ident { get; set; }
protected void TrashIcon_Click(object sender, ImageClickEventArgs e)
{
ResponseMessage.Text = $"Use Control Got it. {Ident}";
}
}
Seems, I have to reload all the controls on the main again to get the click event to execute. I accidentally made this work.
Below Project Visual Studio 2017 - No binaries, except for one image and the rest is only project code.
Main.aspx
<form id="form1" runat="server">
<asp:Button ID="clicker" runat="server" Text="Click Me" />
<asp:PlaceHolder ID="PHwfuc" runat="server"></asp:PlaceHolder>
<asp:Label runat="server" ID="ResponseMessage"></asp:Label>
</form>
Main.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
clicker.Click += new EventHandler(this.ButClick);
if(ViewState["ButClick"] != null)
LoadData();
}
protected void ButClick(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
PlaceHolder placeHolder = new PlaceHolder();
for (int i = 0; i < 2; i++)
{
WFUC1 test = LoadControl("~/WebFormUserControl/WFUC1.ascx") as WFUC1;
test.Ident = i;
placeHolder.Controls.Add(test);
}
PHwfuc.Controls.Add(placeHolder);
ViewState["ButClick"] = true;
}
WFUC1.ascx
<asp:ImageButton runat="server" ID="TrashIcon" ImageUrl = "/images/trash.png" ToolTip = "Delete Address" OnClick="TrashIcon_Click" />
<br />
<asp:Label runat="server" ID="ResponseMessage"></asp:Label>
WFUC1.ascx
public int Ident { get; set; }
public void TrashIcon_Click(object sender, ImageClickEventArgs e)
{
ResponseMessage.Text = $"Use Control Got it. {Ident}";
}
I am using this code from w3schools:
TryIt
How can i integrate it with asp:LinkButton or asp:Button using OnClientClick, while onClick is executing the server code.
Almost a year late to the party, but I've just implemented the same snackbar.
It needs an UpdatePanel and you need to register a client script block on your event handler:
<asp:UpdatePanel runat="server" ID="UpdatePanel1">
<ContentTemplate>
<div>
<asp:Button runat="server" ID="ShowSnackbar" Text="Show Snackbar" OnClick="ShowSnackbar_Click" />
</div>
<div id="snackbar">
<asp:Label runat="server" ID="Snack" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
The codebehind was tricky but it works. On page load, create a string that contains the javascript, then use that string value to register your script block...
private string snackbarScript;
protected void Page_Load(object sender, EventArgs e)
{
snackbarScript = GenerateSnackbarJS();
}
private string GenerateSnackbarJS()
{
var sb = new StringBuilder();
sb.AppendLine("var x = document.getElementById('snackbar');");
sb.AppendLine("x.className = 'show';");
sb.AppendLine("setTimeout(function(){ x.className = x.className.replace('show', ''); }, 3000);");
return sb.ToString();
}
protected void ShowSnackbar_Click(object sender, EventArgs e)
{
Snack.Text = "Here's the snackbar";
ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "snackbar", snackbarScript, true);
}
In my application I have a radschedular , when creating a new appointment I am opening in advance mode by specifying StartInsertingInAdvancedForm="True"
My code is given below
.aspx
<telerik:RadScheduler RenderMode="Lightweight" runat="server" ID="rs_course_schedule" CustomAttributeNames="Completed"
StartInsertingInAdvancedForm="True" StartEditingInAdvancedForm="True"
FirstDayOfWeek="Monday" LastDayOfWeek="Friday" Reminders-Enabled="true" SelectedView="WeekView"
RowHeight="30px" AppointmentStyleMode="Simple" OnAppointmentDataBound="RadScheduler1_AppointmentDataBound"
OnAppointmentCommand="rs_course_schedule_OnAppointmentCommand"
OnAppointmentCreated="RadScheduler1_AppointmentCreated" OverflowBehavior="Auto" Skin="Web20"
OnAppointmentInsert="rs_course_schedule_OnAppointmentInsert">
<AdvancedForm Modal="true"></AdvancedForm>
<AppointmentTemplate>
<div class="appointmentHeader">
<asp:Panel ID="RecurrencePanel" CssClass="rsAptRecurrence" runat="server" Visible="false">
</asp:Panel>
<asp:Panel ID="RecurrenceExceptionPanel" CssClass="rsAptRecurrenceException" runat="server"
Visible="false">
</asp:Panel>
<asp:Panel ID="ReminderPanel" CssClass="rsAptReminder" runat="server" Visible="false">
</asp:Panel>
<%#Eval("Subject") %>
</div>
<div>
Assigned to: <strong>
<asp:Label ID="UserLabel" runat="server" Text='<%# Container.Appointment.Resources.GetResourceByType("Faculty") == null ? "None" : Container.Appointment.Resources.GetResourceByType("Faculty").Text %>'></asp:Label>
</strong>
<br />
<asp:CheckBox ID="CompletedStatusCheckBox" runat="server" Text="Completed? " TextAlign="Left"
Checked='<%# !String.IsNullOrEmpty(Container.Appointment.Attributes["Completed"]) && Boolean.Parse(Container.Appointment.Attributes["Completed"]) %>'
AutoPostBack="true" OnCheckedChanged="CompletedStatusCheckBox_CheckedChanged"></asp:CheckBox>
</div>
</AppointmentTemplate>
<ResourceStyles>
<telerik:ResourceStyleMapping Type="Faculty" Key="1" BackColor="red"></telerik:ResourceStyleMapping>
<telerik:ResourceStyleMapping Type="Faculty" Key="2" BackColor="Pink"></telerik:ResourceStyleMapping>
<telerik:ResourceStyleMapping Type="Faculty" Key="3" BackColor="OrangeRed"></telerik:ResourceStyleMapping>
</ResourceStyles>
</telerik:RadScheduler>
in code behind
public partial class Schedule : System.Web.UI.UserControl
{
#region Object Instantiation
readonly BEL_LMS _objLms = new BEL_LMS();
readonly BL_LMS _blLms = new BL_LMS();
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateSchedular();
AddTeachers();
SetDate();
}
}
private void AddTeachers()
{
_objLms.ActivityId = Session["activity_id"].ToString();
DataTable dtFaculty = _blLms.AssignedFaculty(_objLms);
ResourceType resources = new ResourceType("Faculty");
if (dtFaculty.Rows.Count > 0)
{
resources.DataSource = dtFaculty;
resources.KeyField = "userid";
resources.TextField = "acct_name";
resources.ForeignKeyField = "UserId";
rs_course_schedule.ResourceTypes.Add(resources);
}
}
private void SetDate()
{
rs_course_schedule.SelectedDate = DateTime.Now;
}
private void PopulateSchedular()
{
_objLms.Flag = "fetch";
_objLms.ActivityId = "11";
DataTable dtTable = _blLms.FetchScheduleForCourse(_objLms);
if (dtTable.Rows.Count > 0)
{
rs_course_schedule.DataKeyField = "ID";
rs_course_schedule.DataStartField = "Start";
rs_course_schedule.DataEndField = "End";
rs_course_schedule.DataSubjectField = "Subject";
rs_course_schedule.DataDescriptionField = "Description";
//rs_course_schedule.DataReminderField = "Reminder";
rs_course_schedule.DataSource = dtTable;
rs_course_schedule.DataBind();
}
}
protected void CompletedStatusCheckBox_CheckedChanged(object sender, EventArgs e)
{
CheckBox CompletedStatusCheckBox = (CheckBox)sender;
//Find the appointment object to directly interact with it
SchedulerAppointmentContainer appContainer = (SchedulerAppointmentContainer)CompletedStatusCheckBox.Parent;
Appointment appointment = appContainer.Appointment;
_objLms.ActivityId = appointment.ID.ToString();
_objLms.Flag = "update";
int affectedRow = _blLms.UpdateCourse(_objLms); // update checkbox data for that particular schedule
rs_course_schedule.Rebind();
}
protected void RadScheduler1_AppointmentDataBound(object sender, SchedulerEventArgs e)
{
if (e.Appointment.Attributes["Completed"] == "True")
{
e.Appointment.BackColor = System.Drawing.Color.Red;
}
}
protected void RadScheduler1_AppointmentCreated(object sender, AppointmentCreatedEventArgs e)
{
}
protected void rs_course_schedule_OnAppointmentInsert(object sender, AppointmentInsertEventArgs e)
{
SchedulerDataSource.InsertParameters["End"].DefaultValue = e.Appointment.End.ToString();
SchedulerDataSource.InsertParameters["Start"].DefaultValue = e.Appointment.Start.ToString();
SchedulerDataSource.InsertParameters["Subject"].DefaultValue = e.Appointment.Start.ToString();
SchedulerDataSource.InsertParameters["Description"].DefaultValue = e.Appointment.Description;
SchedulerDataSource.InsertParameters["CourseID"].DefaultValue = "1";
//SchedulerDataSource.InsertParameters["User"].DefaultVal;
}
protected void rs_course_schedule_OnAppointmentCommand(object sender, AppointmentCommandEventArgs e)
{
string name = e.CommandName;
}
}
}
Now when I am trying to insert a new appointment this form is opening
But in Save and Cancel button click is not occurring..
How I can solve this issue ?
I am supposed to update the progress & display the corresponding message on the client side while the function is still under execution at server side.
How can I achieve this?
The function looks like:
protected void Button1_Click(object sender, EventArgs e)
{
string Result = "Success";
if (Result == "Success")
{
Label1.Text = "Plan mst Completed";
Thread.Sleep(2000); //Some functionality here
Label1.Text = "Packing date mst Started";
}
if (Result == "Success")
{
Label1.Text = "Packing date mst Completed";
Thread.Sleep(2000); //Some functionality here
Label1.Text = "Etd mst Started";
}
if (Result == "Success")
{
Label1.Text = "Etd mst Completed";
Thread.Sleep(2000); //Some functionality here
Label1.Text = "Inner box mst Started";
}
}
And I have to update the text of Label1 while the above function is still under execution.
I have tried using AJAX (although I'm still a beginner), but with no success. Here's what I did:
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="10" ontick="Timer1_Tick1">
</asp:Timer>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</form>
And the corresponding events:
protected void Page_Load(object sender, EventArgs e)
{
UpdatePanel1.UpdateMode = UpdatePanelUpdateMode.Conditional;
}
protected void Timer1_Tick1(object sender, EventArgs e)
{
UpdatePanel1.Update();
}
Any other alternatives other than AJAX such as via jQuery or otherwise are also welcome.
these might help you:
http://forums.asp.net/t/1500201.aspx
ASP.NET Asynchronous label update
Environment: ASP NET 2.0 - Production Server does not have Ajax Control Toolkit so no real Control toolkit to use here.
3 RadioButtons List:
List one loads, after postback, the item from list one is used to select a Lab value.
Once a lab value is selected a 3rd radiobuttonlist will populate. There are some textboxes but they are not shown in example. The textboxes postback themselves on changes. If both textboxes are
not empty, a record is created for the session.
Now if the 3rd radiobuttonlist is changed from the default a series of 3 hidden user controls appear which represent 3 levels of reasons for the change ( child/parent records in database ).
The problem I am having is when I select a different item on the radiobuttonlist the radiobutton 3 OnSelectedIndex is firing after my user controls fire. My user controls need the value of the 3rd list to go to the database and get the correct set of records associated with the lab.
The problem is because the last radiobuttonlist is not processed until after the web controls loads, the code to mount the user controls never happens.
Here is the basic HTML code:
<asp:RadioButtonList ID="rdoLab" runat="server" OnSelectedIndexChanged="rdoLab_OnSelectedIndexChange">
</asp:RadioButtonList>
<asp:TextBox ID="textbox1" runat="server" OnTextChanged="TextBoxProcess" />
<asp:TextBox ID="textbox2" runat="server" OnTextChanged="TextBoxProcess" />
<asp:RadioButtonList ID="rdoPrimary" RepeatColumns="3" OnSelectedIndexChanged="rdoPrimary_OnSelectedIndexChanged" runat="server" ToolTip="Select Normal, Hypo or Hyper - Normal is default value." AutoPostBack="True" >
<asp:ListItem Value="3" Text="Normal" Selected="true"/>
<asp:ListItem Value="1" Text="Hypo" />
<asp:ListItem Value="2" Text="Hyper" />
</asp:RadioButtonList>
<asp:Panel ID="UpdLab" runat="server" Visible="true" EnableViewState="true">
<asp:Table ID="tblAdmin" runat="server">
<asp:TableRow>
<asp:TableCell runat="server" id="tblCell1" Visible="false" CssClass="tdCell" VerticalAlign="top">
<uc1:Lab ID="Lab1" runat="server" EnableViewState="true" EnableTheming="true" />
</asp:TableCell>
<asp:TableCell runat="server" ID="tblCell2" Visible="false" CssClass="tdCell" VerticalAlign="top">
<uc1:Lab ID="Lab2" runat="server" EnableViewState="true" EnableTheming="true" />
</asp:TableCell>
<asp:TableCell runat="server" ID="tblCell3" Visible="false" CssClass="tdCell" VerticalAlign="top">
<uc1:Lab ID="Lab3" runat="server" EnableViewState="true" EnableTheming="true" />
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</asp:Panel>
Here is the page behind:
protected override void OnPreLoad(EventArgs e)
{
base.OnPreLoad(e);
GetSessionVars();
if (CommonUI.strTest((string)Session["rdoLabs"]) && CommonUI.strTest((string)Session["rdoPrimary"]) && Convert.ToString(hrdoLabs.Value) == (string)Session["rdoLabs"])
{
divLabLvl.Visible = true;
// Get cboListItems from the web user controls...
Session["ArrLstItems"] = "";
ArrayList ArrLstItems = new ArrayList();
ArrayList GetWuc = GetWUCS();
for (int i = 0; i < GetWuc.Count; i++)
{
Lab wuc = (Lab)GetWuc[i];
CheckBoxList cboItemList = (CheckBoxList)wuc.FindControl("cboItems");
string cboItems = GetCboItemList(cboItemList);
HiddenField hcboItems = (HiddenField)wuc.FindControl("hcboItems");
}
Session["ArrLstItems"] = (ArrayList)ArrLstItems;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DbDataReader ddrGrp = rdoGroups();
if (ddrGrp.HasRows)
{
rdoGroup.DataSource = ddrGrp;
rdoGroup.DataBind();
}
ddrGrp.Close();
}
else
{
DbDataReader ddrLab = rdoUserLabs();
if (ddrLab.HasRows)
{
rdoLabs.DataSource = ddrLab;
rdoLabs.DataBind();
if (CommonUI.strTest((string)Session["rdoLabs"]))
{
if (Convert.ToInt32(Session["rdoLabs"]) > 0)
{
rdoLabs.SelectedValue = (string)Session["rdoLabs"];
SetLabCss();
}
}
}
ddrLab.Close();
}
}
protected void rdoGroup_OnSelectedIndexChanged(object sender, EventArgs e)
{
//...do some stuff
}
protected void rdoLabs_OnSelectedIndexChanged(object sender, EventArgs e)
{
//... reload
}
protected DbDataReader rdoGroups()
{
int group_type_id = GroupTypeId();
Group grp = new Group();
return grp.GetGroups(group_type_id);
}
protected DbDataReader rdoUserLabs()
{
RadioButtonList rdoGrp = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoGroup");
int GroupId = Convert.ToInt32(rdoGrp.SelectedValue);
LabAbnormalReasons lar = new LabAbnormalReasons();
return lar.GetLabsList(GroupId);
}
protected void rdoPrimary_OnSelectedIndexChanged(object sender, EventArgs e)
{
Session["Save"] = ((RadioButtonList)sender).ID;
RadioButtonList rdoGroups = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoGroup");
RadioButtonList rdoLabs = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoLabs");
int UserId = Convert.ToInt32(Session["UserId"]);
int DocId = Convert.ToInt32(Session["DocId"]);
SubmitLab_Data(arrLstItems, arrOthers);
}
protected void GetSessionVars()
{
RadioButtonList rdoGroup = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoGroup");
RadioButtonList rdoPrimary = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoPrimary");
RadioButtonList rdoLabs = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoLabs");
if (rdoGroup.SelectedIndex != -1)
{
Session["rdoGroup"] = (string)rdoGroup.SelectedValue;
}
if (rdoLabs.SelectedIndex != -1)
{
Session["rdoLabs"] = (string)rdoLabs.SelectedValue;
}
if (rdoPrimary.SelectedIndex != -1)
{
Session["rdoPrimary"] = (string)rdoPrimary.SelectedValue;
}
}
Here is example of user code:
THIS CODE NEVER FIRES BECAUSE the 3rd Button List data is not available here :
protected void Page_Load(object sender, EventArgs e)
{
/////*
//// * lab & Primary have been selected...
//// */
int lvl = SetLvlId();
int par_id = GetParentLvl();
Lab wuc = GetWuc(lvl);
if (wuc != null)
{
if (CommonUI.strTest(Convert.ToString(Session["rdoLabs"])) && CommonUI.strTest(Convert.ToString(Session["rdoPrimary"])))
{
// data in data base for this user, lab, doc identifier...
if (Convert.ToInt32(Session["rdoPrimary"]) > 0
{
// have user hdr data - see if item data is mapped...
// do some stuff here
}
}
}
}
I hope this is clear. I've att
---*--- Since original posting:
added simple javascript/OnDataBound
function Primary(object)
{
alert("Value Clicked :" + object);
}
protected void rdoPrimary_DataBound(object sender, EventArgs e)
{
RadioButtonList rdlPrimary = (RadioButtonList)sender;
foreach (ListItem li in rdlPrimary.Items)
{
li.Attributes.Add("onclick", "javascript:Primary('" + li.Value + "')");
}
}
Store and retrieve the values you want to retain in SaveViewState and LoadViewState methods and see if that works for you? Also look to the earlier and later lifecycle events for handling the logic - Init and OnPreRender. This has worked for me in the past.