Move the script creation and attaching to TextBox into OnPreRender method.
When you don't call EnsureChildControls,Page Framework calls it
automatically at the OnPreRender stage at the latest and it works. When you
call it explicitly, running the CreateChildControls happens so early in the
page lifecycle that the Page object isn't yet accessible in the control.
So you get the error because Page is null reference at that point. Otherwise
the logic is correct. You shouldn't access Page at that point, but move the
accessing to the Load (Page is guaranteed to be loaded at that point) and
preferrably to OnPreRender when you can generally think all the necessary
logic that impacts on scripts, is already done and you can safely register
the script.
-
Teemu Keiski
MCP, Microsoft MVP (ASP.NET), AspInsiders member
ASP.NET Forum Moderator, AspAlliance Columnist
http://blogs.aspadvice.com/joteke
Dimitris Pantazopoulos said:
public class SinglePicker : Control, INamingContainer
{
protected TextBox txt = new TextBox();
//...more members here...
public Unit Width
{
get
{
EnsureChildControls(); return txt.Width;
}
set
{
EnsureChildControls();
txt.Width = value;
}
}
//...more methods here....
protected override void CreateChildControls()
{
this.Controls.Add(txt);
String sScript = "<script language=javascript>";
sScript += "function " + csname + "(obj,sS,Params,obj1) {";
sScript += "if (window.event.keyCode == 13) { ";
sScript += "obj1.focus();";
sScript += ".....MORE CODE HERE";
sScript += "window.event.keyCode = 0;} }";
sScript += "</script>";
if (!Page.IsClientScriptBlockRegistered(cskey))
Page.RegisterClientScriptBlock(cskey,sScript);
//bind input textbox to the client script
txt.Attributes["onkeypress"] = csname + "(this," + obj1 + ");";
}
}
The "txt" child control is also attached to a client javascript in CreateChildControls.
The null reference error occurs only when I try to access the Width
property and the error message always points at this line: