ScriptManager.RegisterStartUpScript(...) not working

Ghaleon picture Ghaleon · Apr 18, 2013 · Viewed 17.9k times · Source

I've used this command since I start my new project on ImageButton_Click Event, and it's working perfect in every page that I'm using this: I first, check if there's a field empty if yes then I send this alert.

ScriptManager.RegisterStartupScript(this, typeof(Page), "alert", "alert('No Empty fields are allowed.');", true);  

What I'm doing here: I have 2 textboxes that I type two dates, these dates are used to fill my reportviewer, but before it goes to the reportviewer, I check if it's empty or not.

In this page it's working only in the first time I press the button. I used breakpoint, and it's passing OK throught my conditional IF, but it's not showing the message... Why?
Full Code on a Button_Click Event:

 if (Txt_Dt_Final.Text == "" || Txt_Dt_Inicial.Text == "")
     {
        ScriptManager.RegisterStartupScript(this, typeof(Page), "alert", "alert('No Empty fields are allowed.');", true);
        Txt_Dt_Inicial.Focus();
        return;
     }

UPDATE
Actually, after I press it by the first time, nothing works anymore... Even if I type a valid date, it is not working... I tested it now and, the error only appears, if the error hapens the first time you press the button.
e.g.:
If I type the dates OK, then my reportviewer will return me the result of my report... Then I click on the button with empty textboxes, it will fire the error and show me the message. If I press again it will work fine !

Now, if I press the button with empty fields for the first time, the button does not work anymore ! It just back working if I refresh the page... Why ? o.O
All my others pages are working perfect.

Answer

Prashant picture Prashant · Apr 19, 2013

Your code should work unless you have your ASP controls inside an update panel. If you do then use this instead.

ScriptManager.RegisterStartupScript(updatePanel,updatePanel.GetType()
                                                  , "alert", javaScript, true);