Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Button not firing event

Status
Not open for further replies.

jby1

Programmer
Apr 29, 2003
403
GB
Hi

I have an interesting problem that is driving me mad!

I have a user control, which contains a button. This button fires an event which runs in the code behind. However, when I load the control, the first time I press the button, it posts back (and goes into the Page_Load method), but fails to run it's own event code. If I press it again, it runs the code as it it supposed to.

I do not seem to be getting this problem in any other controls I have (and I have quite a few!).

Anybody any ideas about this one?

Thanks
 
Note that Button1 is a button I dropped onto the form to check if it was a specific problem with the button itself.

Code:
<%@ Control Language="c#" AutoEventWireup="false" Codebehind="AirtimeDealStructureCPTSingle.ascx.cs" Inherits="SalesForecasting.MainPages.Forecast.ControlSections.Platform.AirtimeDealStructureCPTSingle" TargetSchema="[URL unfurl="true"]http://schemas.microsoft.com/intellisense/ie5"%>[/URL]
<table width="100%">
	<tr>
		<td><asp:label id="Label1" CssClass="LabelAlpha" runat="server">Platform Revenue : </asp:label></td>
		<td><asp:textbox id="txtPlatformRevenue" onblur="javascript:DivideCellContents(this.id, this.id.replace('txtPlatformRevenue', 'txtCPTDealPriceGross'), this.id.replace('txtPlatformRevenue', 'lblNumImpacts'))"
				runat="server" cssclass="TextboxNumeric" Width="115px"></asp:textbox><asp:customvalidator id="vldPlatformRevenue" runat="server">*</asp:customvalidator></td>
		<td align="center"><asp:button id="btnRevPerFeed" runat="server" Text="Revenue Per Feed"></asp:button>
			<asp:Button id="Button1" runat="server" Text="Test Button"></asp:Button></td>
	</tr>
	<tr>
		<td><asp:label id="Label2" CssClass="LabelAlpha" runat="server">CPT Deal Price Gross : </asp:label></td>
		<td><asp:textbox id="txtCPTDealPriceGross" onblur="javascript:DivideCellContents(this.id.replace('txtCPTDealPriceGross', 'txtPlatformRevenue'), this.id, this.id.replace('txtCPTDealPriceGross', 'lblNumImpacts'));javascript:SetNetValue(this.id, this.id.replace('txtCPTDealPriceGross', 'lblCPTNet'))"
				runat="server" cssclass="TextboxNumeric" Width="115px"></asp:textbox><asp:customvalidator id="vldCPTDealPriceGross" runat="server">*</asp:customvalidator></td>
		<td><asp:label id="Label3" CssClass="LabelAlpha" runat="server">CPT Net :</asp:label><asp:label id="lblCPTNet" runat="server" cssclass="LabelNumeric" Width="88px">0.00</asp:label></td>
		<td align="right"><asp:label id="Label4" CssClass="LabelAlpha" runat="server">Number of Impacts :  </asp:label><asp:label id="lblNumImpacts" CssClass="LabelNumeric" runat="server" Width="71px">0.00</asp:label></td>
	</tr>
</table>
<hr width="100%" SIZE="1">

and the code behind:

Code:
namespace SalesForecasting.MainPages.Forecast.ControlSections.Platform
{
	using System;
	using System.Data;
	using System.Drawing;
	using System.Text;
	using System.Web;
	using System.Web.UI.WebControls;
	using System.Web.UI.HtmlControls;

	using SalesForecasting.Business;
	using SalesForecasting.js;

	/// <summary>
	///		Summary description for AirtimeDealStructureCPTSingle.
	/// </summary>
	public class AirtimeDealStructureCPTSingle : PlatformBase, SalesForecasting.MainPages.Forecast.ControlSections.IForecastControl
	{
		protected System.Web.UI.WebControls.CustomValidator vldPlatformRevenue;
		protected System.Web.UI.WebControls.CustomValidator vldCPTDealPriceGross;
		protected System.Web.UI.WebControls.Button btnRevPerFeed;
		protected System.Web.UI.WebControls.Label Label1;
		protected System.Web.UI.WebControls.Label Label2;
		protected System.Web.UI.WebControls.Label Label3;
		protected System.Web.UI.WebControls.TextBox TextBox1;
		protected System.Web.UI.WebControls.TextBox txtPlatformRevenue;
		protected System.Web.UI.WebControls.Label lblCPTNet;
		protected System.Web.UI.WebControls.Label Label4;
		protected System.Web.UI.WebControls.TextBox txtCPTDealPriceGross;
		protected System.Web.UI.WebControls.Button Button1;
		protected System.Web.UI.WebControls.Label lblNumImpacts;

		private void Page_Load(object sender, System.EventArgs e)
		{
			if(!this.IsPostBack)
			{
				this.LoadData();
				this.SetIfReadOnly();
			}
			this.SetJavascriptNetAmountCalcValues();
			this.RunJavaScriptCalculationFunctions();
		}

		private void SetIfReadOnly()
		{
			if(this.SessionObj.ForecastReadOnly || this.SessionObj.ForecastDataSet.Forecast[0].StatusId >= StatusMeta.DEAL)
			{
				this.txtCPTDealPriceGross.ReadOnly = true;
				this.txtPlatformRevenue.ReadOnly = true;
			}
			else
			{
				this.txtCPTDealPriceGross.ReadOnly = false;
				this.txtPlatformRevenue.ReadOnly = false;
			}
		}

		private string BuildRevPerFeedString()
		{
			StringBuilder requestString = new StringBuilder(Request.ApplicationPath);

			requestString.Append("/PopupPages/RevPerFeed.aspx?PlatformId=");
			requestString.Append(this.PlatformRow.PlatformId);

			return requestString.ToString();
		}

		private void LoadData()
		{
			this.txtPlatformRevenue.Text = this.PlatformRow.Revenue.ToString();

			if(!this.PlatformRow.IsDealPriceNull())
			{
				this.txtCPTDealPriceGross.Text = this.PlatformRow.DealPrice.ToString();
			}
		}

		private void SetJavascriptNetAmountCalcValues()
		{
			this.Page.RegisterStartupScript("netamounts", 
				JSFunctions.SetNetAmountCalcValues(
					this.txtCPTDealPriceGross.ClientID,
					this.lblCPTNet.ClientID));

			//also set them in the session
			this.SessionObj.ExternalGrossField = this.txtCPTDealPriceGross.ClientID;
			this.SessionObj.ExternalNetField = this.lblCPTNet.ClientID;
		}

		private void RunJavaScriptCalculationFunctions()
		{
			this.JavaScriptDivideCellContentsFunction();
			this.JavaScriptSetNetValueFunction();
		}

		private void JavaScriptSetNetValueFunction()
		{
			this.Page.RegisterStartupScript("setnetvalfunc", 
				JSFunctions.SetNetValueFunction(
					this.txtCPTDealPriceGross.ClientID, 
					this.lblCPTNet.ClientID));
		}

		private void JavaScriptDivideCellContentsFunction()
		{
			this.Page.RegisterStartupScript("divcellcontfunc", 
				JSFunctions.DivideCellContentsFunction(
					this.txtPlatformRevenue.ClientID, 
					this.txtCPTDealPriceGross.ClientID, 
					this.lblNumImpacts.ClientID));
		}

		#region Validation
		private bool IsPageValid
		{
			get
			{
				bool isValid = true;

				if ((!Validation.IsNumber(this.txtPlatformRevenue.Text)) && (this.txtPlatformRevenue.Text.Length > 0))
				{
					this.vldPlatformRevenue.IsValid = false;
					this.vldPlatformRevenue.ErrorMessage = "Platform Revenue must be numerical";
					this.vldPlatformRevenue.Text = "*";
					isValid = false;
				}

				if ((!Validation.IsNumber(this.txtCPTDealPriceGross.Text)) && (this.txtCPTDealPriceGross.Text.Length > 0))
				{
					this.vldCPTDealPriceGross.IsValid = false;
					this.vldCPTDealPriceGross.ErrorMessage = "CPS Deal Price Gross must be numerical";
					this.vldCPTDealPriceGross.Text = "*";
					isValid = false;
				}

				return isValid;
			}
		}
		#endregion Validation

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.btnRevPerFeed.Click += new System.EventHandler(this.btnRevPerFeed_Click);
			this.Button1.Click += new System.EventHandler(this.Button1_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		#region IForecastControl Members
		public bool SaveDataToDataSet()
		{
			bool isValid = this.IsPageValid;

			if(isValid)
			{
				if(this.txtPlatformRevenue.Text.Length > 0)
					this.PlatformRow.Revenue = Convert.ToDecimal(this.txtPlatformRevenue.Text);

				if(this.txtCPTDealPriceGross.Text.Length > 0)
					this.PlatformRow.DealPrice = Convert.ToDecimal(this.txtCPTDealPriceGross.Text);
			}

			return isValid;
		}
		#endregion

		private void btnRevPerFeed_Click(object sender, System.EventArgs e)
		{
			if(this.PlatformRow.GetPlatformFeedRows().Length == 0)
			{
				//must have feeds selected
				this.MsgBox.alert("Feeds must be selected before entering Revenue per Feed");
			}
			else
			{
				if(Validation.IsNumber(this.txtPlatformRevenue.Text))
					this.PlatformRow.Revenue = Convert.ToDecimal(this.txtPlatformRevenue.Text);
				else
					this.PlatformRow.Revenue = 0m;

				this.OpenPopUpNow(
					this.BuildRevPerFeedString(),
					"Revenue Per Region",
					900,
					900,
					true);
			}
		}

		private void Button1_Click(object sender, System.EventArgs e)
		{
			this.MsgBox.alert("Pressed");
		}

		protected override string PlatformType
		{
			get
			{
				return "Airtime";
			}
		}
	}
}
 
You posted all of your code, so i am not sure which button is the problem.. is it button1?
 
It is happening with both of the buttons, but the one I am concerned about is btnRevPerFeed.
 
So, with each button, you are saying that you need to click the button twice before the button's click event fires? Is this correct? Also, is this a windows form or asp.net page




 
This is an ASP.NET page.

Basically, what is happening is that once the page is loaded, a post back must take place before the buttons event fires.

So if the first thing I do when I get on to the form is press the button, is posts back but doesn't run it's click event code.

If I do any action that results in a post back, and then click the button, it works.
 
I have come back to this problem after leaving it for a bit.

As a test, I put a IPostBackDataHandler onto the control, and then put code in the LoadPostData to look at the values posted back for the textbox controls on the form.

On the first postback after loading the control, whilst the controls are represented in the postCollection key list, the values returned for them are null.

On subsequent postbacks, the value is retrieved from them as one would expect.

So it is like the while postback is failing on the first postback, but then works after that.

Any ideas please? I am finding this very odd indeed, although I am sure it must be something simple!
 
Not surprised nobody got this one, as the answer is not contained within this code at all.

On the page, there is a drop down, which does a postback, and depending on what is selected in the drop down, a different control loads into a placeholder. This particular control is one such control.

When the postback occurs, it unloads the old control, and then loads up the new control.

The problem occured because when this happens, the newly loaded control is assigned an id of 2, as the unloaded control already uses the id of 1.

Any data entered into the control is then put into the post collection as part of control 2.

However, when the form posts back again, the control is now assigned the value of 1. Hence it cannot find it's data in the postcollection.

Now that I have identified why the problem is occuring, I now need to work out a solution! Needless to say I will post it if I work it out, but of course I would be very grateful if somebody could push me in the right direction!
 
The solution turned out to be quite simple in the end. All I had to do was to hardcode an id for the user control that I was loading. I know that there will only ever be one of these controls created on the page at a time, so I am happy to do this.
 
One final point on this thread: If you are considering using dynamically loaded controls on your ASP.NET page, then it is essential to get acquainted with the Page Lifecycle. I would have saved myself a lot of bother if I had done this from the start, instead of picking it up as I went along!

In fact, I would recommend learning the Page Lifecycle anyway!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top