I made a Webform that displays time and date, and I wanted to do the same for a Stopwatch, but for some reason the Stopwatch doesn't work.
The time is supposed to start ticking when I click "start", it's supposed to stop when I click "stop", and it is supposed to clear when I click "reset". Instead, when I click start, nothing happens.
Here is my code (C#):
{
public partial class WebForm1 : System.Web.UI.Page
{
private short _secs, _ms;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Timer1_Tick(object sender, EventArgs e)
{
Timerz.Text = DateTime.Now.ToString();
}
protected void Timer2_Tick(object sender, EventArgs e)
{
IncreaseMS();
ShowTime();
}
private void IncreaseMS()
{
if (_ms == 99)
{
_ms = 0;
IncreaseSecs();
}
else
{
_ms++;
}
}
private void IncreaseSecs()
{
if (_secs == 59)
{
_secs = 0;
}
else
{
_secs++;
}
}
protected void start_Click(object sender, EventArgs e)
{
start.Enabled = false;
Timer2.Enabled = true;
}
protected void reset_Click(object sender, EventArgs e)
{
_secs = 0;
_ms = 0;
ShowTime();
}
private void ShowTime()
{
secsText.Text = _secs.ToString("00");
msText.Text = _ms.ToString("00");
}
protected void stop_Click(object sender, EventArgs e)
{
start.Enabled = true;
Timer2.Enabled = false;
}
}
}
Webform, ASP.NET Code:
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
Current time:
<asp:Label ID="Timerz" runat="server"></asp:Label>
</div>
<asp:Timer ID="Timer1" runat="server" Interval="1000"
OnTick="Timer1_Tick">
</asp:Timer>
<div>
<asp:Label ID="secsText" runat="server" Text="00"></asp:Label><asp:Label
ID="colon" runat="server" Text=":"></asp:Label><asp:Label ID="msText"
runat="server" Text="00"></asp:Label>
<br />
<asp:Button ID="start" runat="server" Text="Start" OnClick="start_Click"
/><asp:Button ID="stop" runat="server" Text="Stop" OnClick="stop_Click" />
<asp:Button ID="reset" runat="server" Text="Reset" OnClick="reset_Click" />
</div>
<asp:Timer ID="Timer2" runat="server" OnTick="Timer2_Tick">
</asp:Timer>
</form>
</body>
You haven't set the Interval property on Timer2. The default interval is 60 seconds and you are probably not waiting that long.
Related
I have the following code-behind:
Random rndNum;
int inFirstOne, inSecondOne;
protected void Page_Load(object sender, EventArgs e)
{
rndNum = new Random();
int inFirst = rndNum.Next(1, 51);
int inSecond = rndNum.Next(50, 101);
lblFirst.Text = inFirst.ToString();
inFirstOne = inFirst;
lblSecond.Text = inSecond.ToString();
inSecondOne = inSecond;
}
public void ValidateForm(object sender, EventArgs e)
{
string strNum = tbValidation.Text;
int inCalc = inFirstOne + inSecondOne;
if (inCalc.ToString() == strNum)
{
lblIsValid.Text = "Correct";
}
else
{
lblIsValid.Text = "Please enter the correct result";
lblIsValid.ForeColor = Color.DarkRed;
}
}
ASP.net code:
...
<tr>
<td><h2>What is <asp:Label ID="lblFirst" Text="" CssClass="numGen" ClientIDMode="Static" runat="server" /> + <asp:Label ID="lblSecond" Text="" CssClass="numGen" ClientIDMode="Static" runat="server" />?</h2></td>
<td><asp:TextBox ID="tbValidation" ClientIDMode="Static" CssClass="tbTech" runat="server"></asp:TextBox> <asp:Label ID="lblIsValid" runat="server" /></td>
</tr>
<tr>
<td colspan="2" class="setRight">
<asp:Button ID="SubmitForm" ClientIDMode="Static" runat="server" Text="Submit" OnClick="ValidateForm" CssClass="btn" UseSubmitBehavior="false" />
</td>
</tr>
...
I am always seeing Please enter the correct result message.
How can I modify to ensure when the result is entered it works to validate the calculation from code-behind.
It's not clear how you're filling tbValidation but in any case unless you execute your page_load logic only if request it's not postback, variables inFirstOne and inSecondOnewill be overwritten on button click.
It seems you need to have this
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostback)
{
// do this only if it's the first request
rndNum = new Random();
int inFirst = rndNum.Next(1, 51);
int inSecond = rndNum.Next(50, 101);
lblFirst.Text = inFirst.ToString();
inFirstOne = inFirst;
lblSecond.Text = inSecond.ToString();
inSecondOne = inSecond
}
}
int inCalc = Convert.ToInt32(lblFirst.Text) + Convert.ToInt32(lblSecond.Text); worked.
below is the markup and codebehind.
I am trying to access dropdownlist in the markup from codebehind.
<asp:Repeater runat="server" ID="cataloguesRepeater">
<FooterTemplate>
<table>
<tbody>
<tr>
<td>
<asp:DropDownList runat="server" ID="dropDownList1" />
</td>
</tr>
</tbody>
</table>
</FooterTemplate>
</asp:Repeater>
Codebehind
private void CatalogueItemCommand(object sender, RepeaterCommandEventArgs e)
{
DropDownList dd1 =(DropDownList)e.Item.FindControl("dropDownList1");
}
I always get dd1 as null for some reason. How can access this dropdownlist dd1?
You have to react on the ItemCreated Event:
protected void Page_Load(object sender, EventArgs e)
{
cataloguesRepeater.ItemCreated += cataloguesRepeater_ItemCreated;
cataloguesRepeater.DataSource = new [] { new { title = "item1"}, new { title = "item2" } };
cataloguesRepeater.DataBind();
}
void cataloguesRepeater_ItemCreated(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Footer)
{
var ddl = e.Item.FindControl("dropDownList1");
}
}
I have a page SendResults.aspx that holds a button and a ListView with ItemTemplate set to a user control (3 labels and 2 textboxes) that gets it's data from a matching object.
On Page_Load I fill the List with data (this works well).
When the button is clicked I want to take the user input in the user-control's textboxes and do something with it.
However I always get the initial value and not the updated one.
Here is the code:
The user-control "MatchControl.ascx"
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="MatchControl.ascx.cs" Inherits="TotoMondeal.Controls.MatchControl" %>
<div>
<asp:Image ID="Team1FlagImage" runat="server" />
<asp:Label ID="Team1Label" runat="server" Width="150px"></asp:Label>
<asp:TextBox ID="Team1TextBox" runat="server" MaxLength="2" TextMode="Number" Width="50px" AutoPostBack="true" OnTextChanged="Team1TextBox_TextChanged"></asp:TextBox>
<asp:Label ID="Colon" runat="server" Font-Size="XX-Large" Text=":"></asp:Label>
<asp:TextBox ID="Team2TextBox" runat="server" MaxLength="2" TextMode="Number" Width="50px"></asp:TextBox>
<asp:Label ID="Team2Label" runat="server" Width="150px"></asp:Label>
<asp:Image ID="Team2FlagImage" runat="server" />
</div>
The user-control code-behind:
public partial class MatchControl : System.Web.UI.UserControl
{
public Match Match
{
get
{
object obj = ViewState["Match"];
return (obj == null) ? new Match() : (Match)obj;
}
set
{
ViewState["Match"] = value;
}
}
public string Team1Score
{
get { return Team1TextBox.Text; }
set { Team1TextBox.Text = value; }
}
public string Team2Score
{
get { return Team2TextBox.Text; }
set { Team2TextBox.Text = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
Team1Label.Text = Match.Team1Name;
Team2Label.Text = Match.Team2Name;
Team1TextBox.Text = Match.Team1Score.ToString();
Team2TextBox.Text = Match.Team2Score.ToString();
Team1TextBox.Enabled = Match.EnableTextBox;
Team2TextBox.Enabled = Match.EnableTextBox;
Team1FlagImage.ImageUrl = #"~/FlagImages/" +Match.Team1Name + ".png";
Team2FlagImage.ImageUrl = #"~/FlagImages/" + Match.Team2Name + ".png";
}
protected void Team1TextBox_TextChanged(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox != null)
{
try
{
Match updatedMatch = new Match()
{
MatchId = Match.MatchId,
MatchDate = Match.MatchDate,
Result = Match.Result,
Team1Name = Match.Team1Name,
Team1Score = Convert.ToInt32(textBox.Text),
Team2Name = Match.Team2Name,
Team2Score = Match.Team2Score,
EnableTextBox = Match.EnableTextBox
};
Match = updatedMatch;
}
catch (Exception ex)
{
throw ex;
}
}
}
The SendResults.aspx:
<%# Page Title="שלח תוצאות" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="SendResults.aspx.cs" Inherits="TotoMondeal.SendResults" %>
<%# Register TagPrefix="TOTO" TagName="MatchControl" Src="~/Controls/MatchControl.ascx" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<h2><%: Title %>.</h2>
<div class="jumbotron">
<asp:ListView ID="TodayMatchesList" runat="server">
<ItemTemplate>
<TOTO:MatchControl ID="MatchControl" Match="<%# Container.DataItem %>" runat="server" />
</ItemTemplate>
</asp:ListView>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</div>
</asp:Content>
the SendResults code-behind:
public partial class SendResults : Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<Match> matches = new List<Match>();
matches = Queries.GetTodayMatches(DateTime.Now);
foreach (Match match in matches)
{
match.EnableTextBox = true;
}
this.TodayMatchesList.DataSource = matches;
this.TodayMatchesList.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < TodayMatchesList.Items.Count; i++)
{
MatchControl match = (MatchControl)TodayMatchesList.Items[i].FindControl("MatchControl");
TextBox textBox = (TextBox)match.FindControl("Team1TextBox");
string txt = textBox.Text;
}
}
}
The problem is that in this line:
TextBox textBox = (TextBox)match.FindControl("Team1TextBox");
string txt = textBox.Text;
I always get the initial value from the database, and not the user updated input.
Please help I'm new at this.
Your List is getting overwritten every time you post back. Add this in Page_Load for SendResults
if ( !Page.IsPostBack )
{
List<Match> matches = new List<Match>();
matches = Queries.GetTodayMatches(DateTime.Now);
...etc...
}
In addition to checking IsPostBack you need to handle saving your control properties in the ViewState. As suggested here: User control (ascx) and properties
Example from post:
public string Title {
get { return Convert.ToString(ViewState["Title"]); }
set { ViewState["Title"] = value; }
}
You would do this in your control class.
I have a problem that the value of listbox don't add into the database.
i have a checkboxlist and listbox, first i want to add all selected checkbox value in listbox, it works successfuly, and then i want to add that data of listbox come form checkboxlist to database on button click event, it do not work so how to solve this.
<div id="contentwrapper" class="contentwrapper">
<div id="validation" class="subcontent">
<form class="stdform stdform2" style="border-top:solid 1px #ddd">
<p>
<label>Hotel Name</label>
<span class="field">
<asp:DropDownList ID="ddlHotel" runat="server">
</asp:DropDownList>
</span>
</p>
<p>
<fieldset class="fieldset">
<legend class="legend">Facilities</legend>
<div>
<asp:CheckBoxList ID="cblFacility" runat="server" DataTextField="FacilityName" DataValueField="FacilityID" TextAlign="Right" RepeatColumns="5">
</asp:CheckBoxList>
<div class="clear">
</div>
</div>
</fieldset>
</p>
<p class="stdformbutton">
<asp:Button ID="btnAdd" runat="server" CssClass="radius2" Text="Add" onclick="btnAdd_Click" />
</p>
</form>
</div><!--subcontent-->
</div><!--contentwrapper-->
<div id="Div1" class="contentwrapper">
<div id="Div2" class="subcontent">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<form class="stdform stdform" style="border-top:solid 1px #ddd">
<p>
<span class="field">
<asp:ListBox ID="lstFacility" runat="server" SelectionMode="Multiple"></asp:ListBox><br />
</span>
</p>
<p class="stdformbutton">
<asp:Button ID="btnSubmit" runat="server" CssClass="submit radius2" Text="Submit" onclick="btnSubmit_Click" />
</p>
</form>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAdd" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</div><!--subcontent-->
</div>
AND .cs file is :
protected void Page_Load(object sender, EventArgs e)
{
string myConnectionString = "my connection string";
if (Session["admin"] != null)
{
lblEmail.Text = Session["adminEmail"].ToString();
lblAdmin.Text = "Wel Come " + Session["admin"].ToString();
lblAdmin1.Text = "Wel Come " + Session["admin"].ToString();
}
else
{
Response.Redirect("Login.aspx");
}
if (!Page.IsPostBack)
{
if (Session["hotelID"] != null)
{
ddlHotel.SelectedValue = Session["hotelID"].ToString();
}
ddlHotel.DataSource = dalMST_Hotel.SelectAll(myConnectionString);
ddlHotel.DataTextField = "HotelName";
ddlHotel.DataValueField = "HotelID";
ddlHotel.DataBind();
ddlHotel.Items.Insert(0, "Select Hotel");
BindData();
}
}
private void BindData()
{
string myConnectionString = "my connection string";
cblFacility.DataSource = dalMST_Facility.SelectAll(myConnectionString);
cblFacility.DataBind();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
string s1 = string.Empty;
lstFacility.Items.Clear();
foreach (ListItem item in this.cblFacility.Items)
{
if (item.Selected)
{
lstFacility.Items.Add(item);
}
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string myConnectionString = "my connection string";
Page.Validate();
if (Page.IsValid)
{
DataTable dt = dalMST_FacilityTran.SelectAll(myConnectionString);
int cnt = dt.Rows.Count;
entMST_FacilityTran.HotelID = Convert.ToInt32(ddlHotel.SelectedValue);
entMST_FacilityTran.FacilityID = 0;
entMST_FacilityTran.Created = DateTime.Now;
entMST_FacilityTran.Modified = DateTime.Now;
#region Insert,Update
for (int i = 0; i < lstFacility.Items.Count; i++)
{
int flag = 0;
for (int j = 0; j < cnt; j++)
{
int hotelid = Convert.ToInt32(dt.Rows[j][2].ToString());
int facilityid = Convert.ToInt32(dt.Rows[j][1].ToString());
if (lstFacility.Items[i].Selected)
{
entMST_FacilityTran.FacilityID = Convert.ToInt32(lstFacility.Items[i].Value);
if (entMST_FacilityTran.HotelID == hotelid && entMST_FacilityTran.FacilityID == facilityid)
{
flag = 1;
break;
}
else
{
flag = 0;
}
}
}
if (flag == 0)
{
if (dalMST_FacilityTran.Insert(entMST_FacilityTran, myConnectionString))
{
//txtFacility.Text = "";
//Response.Redirect("AddFacility.aspx");
//return;
}
}
}
Response.Redirect("AddRoomCategory.aspx");
#endregion
}
}
There is problem related to update panel.
Use below code:
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAdd" EventName="Click" />
<asp:PostBackTrigger ControlID="btnSubmit" />
</Triggers>
So submit button cilck event will fire.
Thanks
First You have to remove Nested For Loop
String lstName;
for (int i= 0; i< listBoxEmployeeName.Items.Count;i++)
{
lstName=listBoxEmployeeName.Items[i].Text;//Here your value stored in lstName
//here continue you insert query
}
I have a Repeater control, that I have now reduced to just changing text in a text box when clicking the associated button.
However, this is not happening.
Here is my code so far:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div>
<asp:Repeater ID="rptPdfList" runat="server" OnItemCommand="rptPdfList_ItemCommand">
<HeaderTemplate>
<table>
<tr>
<td>File Name</td>
<td></td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Label ID="lblName" runat="server" Text=<%#Eval("FileName") %>></asp:Label>
</td>
<td>
<asp:Button ID="btnLoad" runat="server" Text="Load" CommandName="LoadDoc"/>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<br />
<asp:Button ID="btnLoad" runat="server" Text="Load" OnClick="btnLoad_Click" /><br />
<iframe runat="server" id="pdfHolder"></iframe>
<br />
<asp:Label ID="lblTest" runat="server" Text="Label"></asp:Label>
</div>
</ContentTemplate>
</asp:UpdatePanel>
Code Behind:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GetFiles();
}
private void GetFiles()
{
rptPdfList.DataSource = Pdf();
rptPdfList.DataBind();
}
protected void rptPdfList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) return;
Label lblName = (Label)e.Item.FindControl("lblName");
switch (e.CommandName)
{
case "LoadDoc":
//xpdfHolder.Attributes.Add("src", "PDF/" + lblName.Text);
lblTest.Text = "test";
lblName.Text = "oops";
break;
}
}
public static List<PdfList> Pdf()
{
string pdfDir = HostingEnvironment.MapPath("~") + #"PDF\";
DirectoryInfo directory = new DirectoryInfo(pdfDir);
FileInfo[] pdfFiles = directory.GetFiles("*.pdf", SearchOption.AllDirectories);
List<PdfList> pdfLists = pdfFiles.Select(pdfFile => new PdfList
{
FileName = pdfFile.Name
}).ToList();
return pdfLists;
}
}
public class PdfList
{
public string FileName { get; set; }
}
Ca anyone see where I went wrong?
Edit, added all the code
Change this:
protected void Page_Load(object sender, EventArgs e)
{
GetFiles();
}
to this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GetFiles();
}
You are calling the GetFiles() each time so it is always returning to the initial state.
I am binding your repeater like this and it works fine for me, Just place your binding function in
if (!Page.IsPostBack)
condition :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
using (DataClassesDataContext dc = new DataClassesDataContext())
{
var v = (from s in dc.t_employees select s).ToList();
rptPdfList.DataSource = v;
rptPdfList.DataBind();
}
}
}
protected void rptPdfList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) return;
Label lblName = (Label)e.Item.FindControl("lblName");
switch (e.CommandName)
{
case "LoadDoc":
//xpdfHolder.Attributes.Add("src", "PDF/" + lblName.Text);
lblTest.Text = "test";
lblName.Text = "oops";
break;
}
}