0

I have onclientclick and onclick events written for Exit button on my webpage. When clicked, it should first execute the update statement and then close the window.

<asp:Button ID="ExitButton" runat="server"  OnClientClick="javaScript:self.close(); return false;" OnClick="ExitButton_Click"  UseSubmitBehavior="false" Text="Exit" Width="102px" CssClass="CssStyle2" Height="29px" />

protected void ExitButton_Click(object sender, EventArgs e)
{
    string sqlUpd = @"UPDATE top (2) [db1].[TestTable] set flag=0 
                     where Date is null and flag=-1";
    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString))
    {
        connection.Open();
        SqlCommand cmdUpd = new SqlCommand(sqlUpd, connection);

        try
        {
            Int32 rows = cmdUpd.ExecuteNonQuery();
            connection.Close();
        }
        catch (Exception eupd)
        {
            lblUpdateErr.Text = "Error occurred in update";
        }
    }
}

Onclientclick is firing but not the onclick i.e. records are not updated. Is there a way to accomplish this?

Thanks Rashmi

Rashmi
  • 121
  • 2
  • 14
  • so, can u suggest another way to update before exiting? – Rashmi Feb 04 '14 at 10:57
  • http://stackoverflow.com/questions/9619395/onclick-not-working-when-i-use-both-onclick-onclientclick – Wolf Feb 04 '14 at 10:58
  • 1
    the above will explain how you can accomplish what you want by modifying your onclientclick a bit this will allow you to use onclick and onclientclick at the same time together on a button i hope this helped if it did il post it as a answer just mark it please let me know if it works – Wolf Feb 04 '14 at 10:59
  • @Wolf, I removed the OnClientClick & UseSubmitBehavior="false". I added ScriptManager.RegisterStartupScript in my ExitButton_Click before the update..voila it works!! – Rashmi Feb 04 '14 at 11:09
  • ok rashmi glad you found the solution ;) – Wolf Feb 04 '14 at 11:18

1 Answers1

2

OnClientClick is executed before the postback happens. It is usually used for things like client side validation where you need to prevent the postback from happening by using return false. Since you are always returning from your handler, the postback will never execute and thus the server side handler will not be called as well.

You need to remove the OnClientClick property and instead call this line in your server side handler:

ScriptManager.RegisterStartupScript(this, this.GetType(), "windowclose", "self.close();", true);

This will cause the window to be closed after the postback executes and the result is returned to the browser. This will also mean that if the update ends with an exception, the window is not closed.

Knaģis
  • 20,827
  • 7
  • 66
  • 80