简体   繁体   中英

NullReferenceException on Page_Load

I'm trying to edit a textbox's text in a Page_Load form on an ASP.NET page, but when I try to edit TextBox1.Text it throws a NullReferenceException because the TextBox has not yet been instantiated. Specifically what I'm trying to implement is this: http://www.codeproject.com/KB/user-controls/popupcalendarcontrol.aspx but it is written for an older version of ASP.NET and does not work for me. Is there a way to instantiate the controls at the start of Page_Load? or another event that I can catch on load? With a normal windows form I would call InitializeComponent() in the constructor.

There are absolutely different events you can attach to but it sounds like the page isn't loading the controls properly because they should be available by that point. You can take a look at the ASP.NET Page Life Cycle for more information.

Does the TextBox sit within a bound control, such as a FormView, GridView, DataList, etc? If so, then the control won't exist until after the databinding happens. Once that event happens, you can do something like

DirectCast(myDataList.SelectedRow.FindControl("myTextBox"), TextBox).Text

I know that I am a bit behind in getting to this question BUT I have found something unusual that I can NOT find documented anywhere. It would appear that IF your page is "under" a Master Page, and IF you refer to ANYTHING on said master page, the controls to your current page are null - EVERYONE of them. I found this out by referencing "Master.Environment" - a public string - during my InitializeCulture method and having the FIRST control on my current (Default.aspx) page be null during Page_Load() - WHATEVER the first control was.

I know I am late but if this can help ANYBODY, I want the word out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM