简体   繁体   English

Page_Load 上的 NullReferenceException

[英]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.我正在尝试在 ASP.NET 页面上的 Page_Load 表单中编辑文本框的文本,但是当我尝试编辑 TextBox1.Text 时,它会引发 NullReferenceException,因为尚未实例化 TextBox。 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.具体来说,我要实现的是: http://www.codeproject.com/KB/user-controls/popupcalendarcontrol.aspx但它是为旧版本的 ASP.NET 编写的,对我不起作用。 Is there a way to instantiate the controls at the start of Page_Load?有没有办法在 Page_Load 开始时实例化控件? or another event that I can catch on load?或者我可以在负载上捕获的其他事件? With a normal windows form I would call InitializeComponent() in the constructor.使用普通的 windows 表单,我会在构造函数中调用 InitializeComponent()。

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.您可以查看ASP.NET 页面生命周期以获取更多信息。

Does the TextBox sit within a bound control, such as a FormView, GridView, DataList, etc? TextBox 是否位于绑定控件中,例如 FormView、GridView、DataList 等? 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.如果您的页面位于母版页“下”,并且如果您在所述母版页上引用任何内容,则似乎您当前页面的控件是 null - 其中每个人。 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.我通过在我的 InitializeCulture 方法期间引用“Master.Environment” - 一个公共字符串 - 并在 Page_Load() 期间让我当前(Default.aspx)页面上的第一个控件是 null 发现了这一点 - 无论第一个控件是什么。

I know I am late but if this can help ANYBODY, I want the word out.我知道我迟到了,但如果这可以帮助任何人,我想要这个词。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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