Textbox Value not set on Page_Load, but set by the time the page renders

I have a form with 3 textboxes that I create dynamically.

The 3 are txtAge, txtUnits and txtPrice.

txtPrice is set by getting a value using txtAge's value and multiplying it by txtUnit's value.

The controls are currently created OnInit (though I've tried doing it on Page Load and it doesn't change anything).

During my Page_Load method I find the textboxes using the unique names that I give them and when I check to see if they have a value, they are blank, however once the page loads they have a value just like I would expect them to.

For example if I change txtUnits from "5" to "4" and then cause a postback, on Page_Load txtUnits has no value but  by the time the page Renders the value is "4".

I thought the order went like this:

Page.Init
Page.LoadViewState
Page.ProcessPostData
Page.Load
Change events for controls
Server side validation
Button.Click or Button.Command events
Page.PreRender
Page.SaveViewState
Page.Render

Which means by Page.Load I should have data in my textboxes.  What am I missing?

0
jwright
10/3/2008 7:03:39 PM
asp.net.web-forms 93655 articles. 6 followers. Follow

8 Replies
755 Views

Similar Articles

[PageSpeed] 48

 So.....no one?

0
jwright
10/6/2008 3:16:27 PM

 Hiya,

 I'm guessing its because you are creating the control dynamically at each page refresh (ie postback). Could you place the code that creates the controls in a block like

if (!page.IsPostBack)

{

 // create control here

}

As I say this is an untested guess, but maybe worth a try.

HTH

0
SimonRigby
10/6/2008 3:37:58 PM

I appreciate the advice, however it won't work for me because if I don't recreate the controls on Postback then they definitely won't have any values.

The problem is that the controls are being recreated and they are being reassigned their values just like they should be...but that value is not being reassigned until after the code I need to check the new value has run through.

0
jwright
10/6/2008 4:26:25 PM

Hi  jwright@watlow.com,

Sorry, I do not know what is the missing, as a solution, I worte a demo for your reference,

 

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    protected void Page_Load(object sender, EventArgs e)
    {
        TextBox txtTemplate = new TextBox();
        txtTemplate.ID = "txtAge";
        txtTemplate.AutoPostBack = true;
        txtTemplate.TextChanged += new EventHandler(txtTemplate_TextChanged);
        form1.Controls.Add(txtTemplate);

        txtTemplate = new TextBox();
        txtTemplate.ID = "txtUnits";
        txtTemplate.AutoPostBack = true;
        txtTemplate.TextChanged += new EventHandler(txtTemplate_TextChanged);
        form1.Controls.Add(txtTemplate);

        txtTemplate = new TextBox();
        txtTemplate.ID = "txtPrice";
        txtTemplate.AutoPostBack = true;
        txtTemplate.TextChanged += new EventHandler(txtTemplate_TextChanged);
        form1.Controls.Add(txtTemplate);
    }
    protected void txtTemplate_TextChanged(object sender, EventArgs e)
    {
        if ((form1.FindControl("txtAge") as TextBox).Text != "" && (form1.FindControl("txtUnits") as TextBox).Text != "")
        {
            string s1 = (form1.FindControl("txtAge") as TextBox).Text;
            string s2 = (form1.FindControl("txtUnits") as TextBox).Text;
            float f1 = float.Parse(s1);// please input the number in the TextBox
            float f2 = float.Parse(s2);// please input the number in the TextBox
            float result = f1 * f2;
            (form1.FindControl("txtPrice") as TextBox).Text = result.ToString();
        }

    }

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>P</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    </form>
</body>
</html>
 

 


Hong-Gang Chen
Microsoft Online Community Support
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
0
Hong
10/7/2008 9:40:50 AM

 That is pretty much exactly what I do (with some things in between obviously since the page is alot more complicated than that) and it's still not working correctly.

0
jwright
10/7/2008 3:54:43 PM

 Maybe time to post your code??

0
SimonRigby
10/7/2008 4:04:07 PM

 No can do. (Non-Disclosure Agreement)

plus...the code is spread across multiple files (part is on a user control) and is split up amongst hundreds of lines of code.

:(

 

I suppose I'll just work at figuring out a different way to do it.

 

Thanks for the help.

0
jwright
10/7/2008 4:12:31 PM

jwright@watlow.com:

 That is pretty much exactly what I do (with some things in between obviously since the page is alot more complicated than that) and it's still not working correctly.

Hi jwright@watlow.com,

I have tested my code, I am sure it works.  Hope you test again.

For testing, please create a ASPX page with C# language, and switch to the "Source" view, copy and paste my code instead of the page code, and set this page as start page, and run.


Hong-Gang Chen
Microsoft Online Community Support
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
0
Hong
10/8/2008 12:49:06 AM
Reply:

Similar Artilces:

How to set value that get from the other web page for TextBox when insert into database ?
Hi,   I want to insert into database a record , one textbox value get from use input, the other 2 get from the web page. how I should write the code? here is the code: --------------------------VB   Response.Redirect("~/TE/Print test.aspx?id=" & DetailsView1.DataKey("ID") & "&designer_id=" & Staff.IdByLogin(User.Identity.Name)) form this I get id and designer_id in TE/Print test.aspx. ----------------------------ASPX  <asp:FormView ID="FormView2" runat="server" DataKeyNames="ID&...

The value set to controls at client side donot persist for each page load, else it is again set to the default value...??
 I am trying to set date to the textbox field using javascript (Client side), the function is as follows. function From_calendarPicker(){                                var    sDPath = "../Calender.aspx";                 var    oWin = window.showModalDialog(sDPath, null, "dialogWidth:300px;dialogHeight:250px;help:0;status:0;scroll:0;center:1");  &nbs...

cascading dropdown set it's value only once but not on subsequent postbacks,web service recieve the value but can't set in dropdown
i have a dropdown named uxcommunity which is a dropdown and contain text in format ##-####-#### . and 2 more dropdowns province and district where province filters district. i get the first 2 characters ##  for session("province") and #### for session("District") and i have button to do the postback. first when the form loads and i click the button it get the value and select appropraite items in to dropdown province and district. but when i change the province dropdown content and district dropdown content and click the button , session will take correct...

Set Selected value from Gridview in page 2 into EditTemplate's Textbox in page 1
Hi All,  I have 2 ASP.NET pages and they have both using Gridview.On page 1, Edit enbale and in the EditTemplate I create a button next to the Textbox when user click,it need to open page 2 (ie, Page 2 serve as a lookup table) and once the user select a row on page I need to set the value let say rows.Cell[1] into the textbox in page 1 and page 2 close itself. I tried to use session but it seem like the session die as soon as page 2 close itself.can someone pls post a script such when user click Select in page 2, I need to set the value for the selected row into the textbox in page 1 ...

When i open my page I want set file control and textboxes fields with values in page load event
 Hi , I have input text and  inputFile  control  <input type="text" id=" txtServerName" runat="server"/><input type="text" id="FileName" name="FileName" runat="server" /><input type="file" id="FileName1" name="FileName1" class="fileupload" runat="server" size="1" onpropertychange="FileName_PropertyChange();"> and i  applied this  css and javascript <script type="text/javascript"> &...

Values in SMTP settings in web.config override manual settings
Hi,I'm trying to load a sifferent set of smtp settings than the ones dictated by web.config, this way (in global.asax):                Configuration configurationFile = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/web.config");                System.Net.Configuration.MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as System.Net.Configuration...

Web Site times out
My web site times out when I run a SQL Stored procedure that takes 47 seconds. I thought that I had prevented this by setting time limits to 600 seconds for both the SQL connection and httpRuntime  My web.config contains: -<add name="ConnectionString" connectionString="Data Source=xxxx;Initial Catalog=gdb;Persist Security Info=True;User ID=xxxxx;Password=xxxxx;connection timeout=600" providerName="System.Data.SqlClient"/>and <httpRuntime maxRequestLength="8192" executionTimeout="600"/> Is there anywhere else that I should...

Setting a textbox text value after the page has databind
Hi I’ve created a basic web page with a SQLdataSource which returns all rows where the date value is within a date range defined by two text box controls. What I’d like to do is set the default text value of the two text boxes to ‘please enter a date’, but this causes a SQL error – understandable. I’ve tried to use: protected void Page_Unload(object sender, EventArgs e){         TextBox_DateFrom.Text = "Enter the date from value";} … but for some reason, no text is added – seemed a bit strange? I need to find a way of setting the de...

Setting textbox value on MasterPage from Content Page.
Hello, all. I'm having troubles with losing session values from within a component, so I've decided to write a value to a hidden textbox on the master page, which I hope will remain in viewstate and be called each time a new page loads. But, for the life of me, I can't seem to set the value from the default content page, which does nothing more than set the "language" value and then redirect into the application.  The value should then be avialable for all requests.  All the examples I've seen are the same, but none work for me... Here's excerpt from the current code: /***** Ma...

Set DropDownList to value of textbox on page load
Hi, I have a drop down list with three values a,b,c.  When the page loads if the value of textbox1 is 'b' - is it possible to set the dropdownlist value to 'b'? Thanks,   Fiorano DropDownList ddl = new DropDownList(); ListItem item = ddl.Items.FindByValue("b");if (item != null) {item.Selected = true; }All that glitters is gold-Only shooting stars break the mold. This may be a bit simpler:   protected void Page_Load(object sender, EventArgs e) { DropDownList1.SelectedValue = TextBox1.Text;  Steve Wellens My blog ...

Is there any possible way that forms authentication can work on a web farm w/o each servers machine key values being set to the same thing?i have a site that is on a web farm and the servers dont have
 Is there any possible way that forms authentication can work on a web farm w/o each servers machine key values being set to the same thing?i have a site that is on a web farm and the servers dont have the machine keys set......but the forms authentication works fine. "Only when we are no longer afraid do we begin to live" -D. Thompson // f bush. ----------- "No man succeeds without a good woman behind him. Wife or mother, if it is both, he is twice blessed indeed." -Harold MacMillan A couple of things spring to mind. 1. Some form of "st...

Word OLE again, this time setting values in forms.
My apologies in advance for dragging this thru the mud but I'm having a heck of time with OLE ... Can anyone point me to some example code or tell me what I should do, to set field values in a Word 97 form document using OLE? I have found some PB OLE examples but they don't work. I'm assuming it's because I have a form document that is locked and I'm trying to set the values of the form fields rather than just change some text. I have set up Bookmarks for each field I need to access and have tried using many of the methods from various web pages but I...

Setting Values in User Control Based on Session Vars Set After Page Load
Ok ... I have a web app that includes multiple custom user controls on each page. I would like to set values in my "header" control (first one loaded on page) based on session variables I set upon user events in the parent page. For example, the user would select a value from a dropdownlist that sets a session variable, say a certain account number, and I would like that value to appear in the header control on the post back. If I put code to check for the session variable in the page load of the control, it won't show up until a subsequent postback. Basically, I need to ...

Web.Config and Settings.settings
Say you have a web application that references a class library.  How can you put values in the web.config file so that the settings.Designer.vb file (in the class library) can access them?  I have just cut and pasted the "applicationSettings" section from the app.config of the class library to the web.config of the webApp, but this does not seem to have worked.E.G.  I have a setting "MyTestURL" in the settings.settings file of the class library. This results in an autogenerated property  "MyTestURL" in the corresponding settings.designer file...

Web resources about - Textbox Value not set on Page_Load, but set by the time the page renders - asp.net.web-forms

ASP.NET - Wikipedia, the free encyclopedia
ASP.NET is a server-side Web application framework designed for Web development to produce dynamic Web pages . It was developed by Microsoft ...

News
Delivering NSW rugby fans the latest news, rugby match fixtures & results, video and rugby statistics for the Shute Shield - NSW Premier Rugby ...

操作失败信息_Foosun Inc.
System.IO.FileNotFoundException: Could not find file 'D:\wwwroot\2011askci\CIlucenet\search_reports\_1bv.cfs'.File name: 'D:\wwwroot\2011ask ...

FAIL can impress, too
I mentioned that a quick way to setup things for me to think that a candidate is a bad idea is to send us a UI project. This is usually a very ...

C# dotnet SQL editor (codebehind side)
... editor (webform side) I've explained the purpose of this "exercise" and suggested a webform proposal for this diy SQL... protected void Page_Load(object ...

Silverlight, FireFox and 100%
In my last post I mentioned something nice about FireFox. In this post I’ll talk something not that nice about FireFox and the way we, more or ...

Case insensitive compare on string in ASP.NET - Coders Grid
... ; using System.Web.UI.WebControls ; namespace WebApplication1 { public partial class Compare : System. Web . UI . Page { protected void Page_Load ...

Response.Redirect() executes too soon on the Server.
-*+I’ve seen this question a couple of times in various situations. The first involves Javascript and the second involves server side code. Both ...

Boost ASP.NET performance with deferred content loading
A comprehensive example of how to improve the perceived speed of your pages, by implementing user controls to encapsulate secondary content and ...

Visual Studio 11 Beta in Context
... partial class Categories : System.Web.UI.Page { private readonly DemoWhateverDataContext _db = new DemoWhateverDataContext(); public void Page_Load() ...

Resources last updated: 11/29/2015 9:38:22 PM