My problem is that I can only seem to click the button once, if I click multiple times it's like it's dead. Doesn't do anything. So if I click it once it sets the text to "Works". How come it doesn't keep alternating between values when I click many times?
I have the following C# code (I know I am using too many namespaces, but please disregard that);
using System;
using System.Collections.Generic;
using System.Data;
using System.Web.Security;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "Click to test";
}
protected void Click(object sender, EventArgs e)
{
if (Label1.Text == "Works")
{
Label1.Text = "Try again";
}
else
{
Label1.Text = "Works";
}
}
}
And here is the ASPX code;
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Click" />
</form>
</body>
</html>
In your Page_Load you need to check IsPostBack If it is a postback you shouldn't set the control value.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
Label1.Text = "Click to test";
}
Or in the case of an ajax update, it's IsAutoPostback (I think!)
The solution is what Sophie88 suggested, but I wanted to add some additional detail to explain exactly what's happening.
User initially requests page: (IsPostBack is false )
Aspx markup is parsed: Label1.Text is "Label"
Page_Load fires, sets Label1.Text to "Click to test"
User clicks button the first time: (IsPostBack is true)
Aspx markup is parsed: Label1.Text is "Label"
ViewState is restored, Label1.Text becomes "Click to test"
Page_Load runs, sets Label1.Text to "Click to test"
Click method runs. Label1.Text == "Click to test", so Label1.Text set to "Works"
User clicks button second time: (IsPostBack is true)
Aspx markup is parsed: Label1.Text is "Label"
ViewState is restored, Label1.Text becomes "Works"
Page_Load runs, sets Label1.Text to "Click to test"
Click method runs. Label1.Text == "Click to test", so Label1.Text set to "Works"
Why are you setting the Label1.Text in the page_load?
IN your markup, just set the Text property to "Click to test"
<asp:Label ID="Label1" runat="server" Text="Click to test"></asp:Label>
Each time you load the page you are setting the Label1.Text to "Click to test" (Page_Load happens every time the page is displayed), then the click event is triggered and correctly sees that the label isn't set to "Works" and so sets it to "Works".
How to fix it, see Sophie88's answer.
Related
I have an ASP.net WebForm. The markup is like:
<div>
<input type="text" id="input" runat="server" value=" " />
<asp:Button Text="send" OnClick="btnsend_Click" ID="btnsend" runat="server" />
</div>
This HTML is generated at runtime . The events are defined in the code behind file.
I need to add these controls at runtime. I tried to use the Literal-Control but the controls are working just like HTML Controls and not like ASP.net Controls.
EDIT:
Note: The Project type should be Website, not a web Application. Web application won't support on demand compilation where website yes, it is.
If I understood currectly, you want to take the Markup from User which contains even asp.net controls and scriplets too.
if this is the case, Follow below steps:
Create a dummy .ascx control file, like DynamicMarkup.ascx with empty content
Add this user control to the page (xxxx.aspx) where you want to show this control statically so it registered to the page
<%# Register src="~/DynamicMarkup.ascx"
tagname="DynamicMarkup" tagprefix="MyASP" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder runat="server"
ID="DynamicMarkupContainer" ></asp:PlaceHolder>
</div>
</form>
</body>
</html>
Write user input markup (may be get from database based on your criteria) to the DynamicMarkup.ascx file in page OnInit of the page (xxxx.aspx) And the create object of this DynamicMarkup
DynamicMarkup dynamicMarkup = LoadControl("~/DynamicMarkup.ascx") as
DynamicMarkup;
DynamicMarkupContainer.Controls.Add(ucSimpleControl);
I have not tested this approach, Just give a thought, With this you may get some session overwriting issue which you need handle.
Hope this will help!!
OLD:
is this the one that you are expecting? TextBox, and Button controls are available in System.Web.UI.WebControls namespace.
void Page_Load(Object sender, EventArgs e)
{
TextBox input = new TextBox();
input.Id ="input";
this.PlaceHolder.Controls.Add(input);
Button btnSend=new Button();
btnSend.Id ="btnSend";
btnSend.Text="Send";
btnSend.Click += new EventHandler(btnSend_Click);
this.PlaceHolder.Controls.Add(btnSend);
}
void btnSend_Click(object sender, EventArgs e)
{
// throw new NotImplementedException();
}
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:PlaceHolder ID="phHolder" runat="server"></asp:PlaceHolder>
</form>
</body>
</html>
code behind :
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Init()
{
GenerateContorls();
}
protected void Page_Load(object sender, EventArgs e)
{
}
private void GenerateContorls()
{
TextBox newTxt = new TextBox() { ID = "txtsend" };
Button newBtn = new Button() { Text = "Send", ID = "btnsend" };
newBtn.Click += btnsend_Click;
phHolder.Controls.Add(newTxt);
phHolder.Controls.Add(newBtn);
}
protected void btnsend_Click(object sender, EventArgs e)
{
TextBox txt = (TextBox)this.FindControl("txtsend");
//your code
}
}
hope it helps
In the sample code there are two listboxes. In ListBox1 the items are defined in Default.aspx. In ListBox2 they are defined in the codefile. ListBox1 behaves as expected, the text box is updated whenever an item is selected. When ListBox2 triggers an event the selectedindex is always -1.
Default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="ListBox1" runat="server" OnSelectedIndexChanged="lb1_OnSelectedIndexChanged" AutoPostBack="true">
<asp:ListItem>a</asp:ListItem>
<asp:ListItem>b</asp:ListItem>
</asp:ListBox>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:ListBox ID="ListBox2" runat="server" OnSelectedIndexChanged="lb1_OnSelectedIndexChanged" AutoPostBack="true">
</asp:ListBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
Default.aspx.cs:
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<string> ab = new List<string>();
ab.Add("a");
ab.Add("b");
ListBox2.DataSource = ab;
ListBox2.DataBind();
ListBox1.SelectedIndexChanged += new EventHandler(lb1_OnSelectedIndexChanged);
ListBox2.SelectedIndexChanged += new EventHandler(lb2_OnSelectedIndexChanged);
}
protected void lb1_OnSelectedIndexChanged(object sender, EventArgs e)
{
if (ListBox1.SelectedIndex != -1)
{
TextBox1.Text = ListBox1.SelectedItem.Text;
}
}
protected void lb2_OnSelectedIndexChanged(object sender, EventArgs e)
{
if (ListBox2.SelectedIndex != -1)
{
TextBox2.Text = ListBox2.SelectedItem.Text;
}
}
}
The list of items has been moved to Default.aspx to get it working, but I'd really like to know what I'm doing wrong with this. -- Thanks!
You can't databind ListBox2 on every page load. Try:
Page_Load()...
{
if(!IsPostBack)
{
//databind listbox2
}
}
Try reading up a bit on the ASP.NET page lifecycle. On the postback, the ListBox2 will have it's correct state due to viewstate.
Your current code resets it. Hence the -1.
During the page_load, I disable the timer. When I pressed Button1, I enable the timer, but the page refreshes. Therefore, it never reaches the timer_tick1. I need to show a popup after a certain amount of time a button is clicked. How do I prevent the refresh from happening?
Alerts Class
public static class Alert
{
public static void Show(string message, Page page)
{
// replaces the quotations to follow the script syntax
// quotations are interpretated as \\' in script code
string cleanMessage = message.Replace("'", "\\'");
string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";
// Gets the executing web page
Page tempPage = page;
// Checks if the handler is a Page and that the script isn't already on the page
if (tempPage != null & !tempPage.ClientScript.IsClientScriptBlockRegistered("alert"))
{
tempPage.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script); // this isn't working, but it works on a button click event.
}
}
}
Page Class
public partial class Test1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostback) {
Timer1.Enabled = false;
Label2.Text = "Panel refreshed at: " +
DateTime.Now.ToLongTimeString(); // Checks if page reloads
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{ // i added a breakpoint here. It doesn't even pass through.
Alert.Show("hehehehe", this); //PopUp Shows up.
Timer1.Enabled = false; //Cancels Timer
Label1.Text = "Panel refreshed at: " +
DateTime.Now.ToLongTimeString(); // Checks if update panel reloads
}
protected void Button1_Click1(object sender, EventArgs e)
{
Timer1.Enabled = true; //Starts Timer. It seems to refresh the page.
}
}
script
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Test1.aspx.cs" Inherits="Test1" %>
<%# Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Namespace="System.Web.UI" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<script type="text/javascript">
function delayer() {
setTimeout (function () {ShowPopUp()}, 15000);
}
delayer();
</script>
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick" Interval="1000" Enabled="true">
</asp:Timer>
<asp:Label ID="Label1" runat="server" Text="PanelNotRefreshedYet"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="ShowPopUp();" />
</form>
</body>
</html>
I think you're confused. Timer1 is a server side control. So it will fire on the server side, if you're still processing the page, that is, and will have no effect on the client side. By the time it fires in your code, the page has likely already rendered so you'll see no effect from that Timer1 object's Timer1_Tick event. Since the page has completed rendering, you can't inject new JavaScript, modify the page, or anything like that. Remember that web development is a disconnected thing. You send a request, you get a response. There are no events by nature of the web. There are libraries out there for triggering events and such but I think that's way beyond what you're trying to achieve.
For client side "timer" you need to use JavaScript setTimeout method, which you have verified as working and is the proper way for you to achieve the delay you're looking to implement.
setTimeout (function () {ShowPopUp()}, 15000);
If you still want to do it in your Alert class, then get rid of Timer1 and have your Alert class inject the timeout in JavaScript:
protected void Button1_Click1(object sender, EventArgs e)
{
Alert.Show("He heee", this);
}
And in Alert, change your script to:
string script = "<script type=\"text/javascript\">setTimeout(function() {alert('" + cleanMessage + "');}, 15000);</script>";
Your button is doing a postback, so yes the page will be refreshed and your Page_Load function will run again. You should test for this using the IsPostback property.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostback) {
Timer1.Enabled = false;
Label2.Text = "Panel refreshed at: " +
DateTime.Now.ToLongTimeString(); // Checks if page reloads
}
}
You might want to look at showing the alert using JavaScript on the page rather than running it server side tho.
<script type="text/javascript">
function showPopup()
{
alert("Hey, click something already");
}
function delayer() {
setTimeout (showPopUp, 15000);
}
delayer();
</script>
Just put your message like this. Probably easier if your logic is simple.
I'm absolutliy confused.
I try to Change the default Text for a Textbox.
Here a simple Code to reproduce the Problem.
TextBox Textbox1 and the label become updated on any click to the Button.
Textbox var will never get updated. Only on first PageLoad.
The Problem is, I have to add my Textboxes from Code behind and not in aspx Page.
Any Ideas whats going on and how I can get it working?
%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="tbtester.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div >
<asp:Panel ID="mypanel" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
</asp:Panel>
</div>
</form>
</body>
</html>
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace tbtester
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Web.UI.WebControls.TextBox var = new System.Web.UI.WebControls.TextBox();
//if (!this.Page.IsPostBack)
Label test = new Label();
mypanel.Controls.Add(test);
mypanel.Controls.Add(var);
var.Text = DateTime.Now.ToLongTimeString();
test.Text = DateTime.Now.ToLongTimeString();
var.ReadOnly = false;
TextBox1.Text = DateTime.Now.ToLongTimeString();
}
}
}
Disable its read only flag before adding it to your panel:
TextBox var = new TextBox();
var.ReadOnly = false;
mypanel.Controls.Add(var);
I have created a TextBox dynamically, and i am getting the value of the textbox when i click the button. But the value entered in the dynamic textbox gets empty when i click the button.
Below is my ASPX Code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Reports.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:DropDownList ID="DropDownList1" runat="server"
onselectedindexchanged="DropDownList1_SelectedIndexChanged" AutoPostBack = "true">
<asp:ListItem>Text</asp:ListItem>
<asp:ListItem>Check</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="GetTextBoxValue" />
</form>
</body>
</html>
CodeBehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Reports
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox TB = new TextBox();
TB.ID = "abc";
form1.Controls.Add(TB);
Response.Write(Request.Form["abc"]);
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
createcontrol();
}
protected void createcontrol()
{
if (DropDownList1.SelectedValue.ToLower().Trim() == "text")
{
TextBox TB = new TextBox();
TB.ID = "abc";
form1.Controls.Add(TB);
}
}
}
}
When you use dynamic controls in .NET and want their values to be accessible after postback you need to create them within the Page_Init method of the page. In essence its not working because ViewState has already been set by the time you created the controls. See this guide for detailed info on this topic https://web.archive.org/web/20211020131055/https://www.4guysfromrolla.com/articles/081402-1.aspx . To fix the problem elevate your Textbox instantiation code to the Page_Init method and all should be well.