I’m creating a custom web control, basically extending RadTextBox since it doesn’t have onBlur() event. I added a script in the .ascx file. I am trying to register the script but it fails. I’m not sure what I’m missing here.
<script language="javascript">
function handleLostFocus(o) {
aler(o.toString());
}
</script>
public partial class MyTextBox : RadTextBox, IScriptControl
{
private void RegisterScripts()
{
try
{
String csname1 = "handleLostFocus";
Type cstype = this.GetType();
String cstext1 = "alert('Hello World');";
ScriptManager.RegisterStartupScript(this, cstype, csname1, cstext1, true);
}
catch (Exception ex)
{
}
}
public MyTextBox()
{
Attributes.Add("padding", "5px");
Skin = "Office2007";
Attributes.Add("onBlur", "handleLostFocus(this);");
RegisterScripts();
}
}
You’re calling RegisterScripts in the constructor of your class. Your control is not yet in the Page in the constructor and hence you cannot register a startup script for a control that’s not even on the Page yet.
I suspect the best place to do this would be the Init method. You can do this by replacing the call in your constructor with this:
Init += (s,e) => { RegisterScripts(); };(You could also create a full Init method on your control, but this is the short-hand version)