title: Invoke OnClientClick of button in code behind
body: <p>I have an button in my aspx web page, which should be 'clicked' in my code behind c# code. The OnClientClick method then call a JS confirm dialog box and so the btn_Click function only get executed when user click 'OK'...</p>
  
  <p>This is my code so far:
  <strong>Variante 1</strong></p>
  
  <p>aspx:</p>
  
  <pre><code>&lt;asp:Button runat="server" ID="btnConfirm" Text="Confirm" OnClick="btnConfirm_Click" /&gt;
  </code></pre>
  
  <p>aspx.cs:</p>
  
  <pre><code>protected void Page_Load(object sender, EventArgs e)
  {
         // set OnClientClick 
         btnConfirm.OnClientClick = "confirm('Save in DB?');";
  
         // invoke method
         Type t = typeof(System.Web.UI.WebControls.Button);
         object[] p = new object[1];
         p[0] = EventArgs.Empty;
         MethodInfo m = t.GetMethod("OnClick", BindingFlags.NonPublic | BindingFlags.Instance);
         m.Invoke(btnConfirm, p);
  }
  protected void btnConfirm_Click(object sender, EventArgs e)
      {
          //save something in database
      }
  </code></pre>
  
  <p>Got code samples by: <a href="http://forums.asp.net/t/1046550.aspx?How+do+you+raise+a+button+click+event+from+outside+the+button+" rel="nofollow">http://forums.asp.net/t/1046550.aspx?How+do+you+raise+a+button+click+event+from+outside+the+button+</a></p>
  
  <p>I want to call the OnClientClick method, but when I replace 'OnClick' with 'OnClientClick' this error appear:</p>
  
  <blockquote>
    <p>System.NullReferenceException was unhandled by user code
      Message=Object reference not set to an instance of an object.</p>
  </blockquote>
  
  <p>Edit:
  <strong>Variante 2:</strong></p>
  
  <p>I tried to rewrite my program like this:
  aspx:</p>
  
  <pre><code>&lt;script language="javascript"&gt;
  function invokeButtonClick() {
          document.getElementById("btnConfirm").click();
      }
  
      function Validate() {
          return confirm('Save in db?');
      }
  &lt;/script&gt;
  &lt;asp:Button runat="server" ID="btnConfirm" Text="Confirm" OnClick="btnConfirm_Click" OnClientClick="return Validate();" /&gt;
  </code></pre>
  
  <p>aspx:cs: </p>
  
  <pre><code>protected void Page_Load(object sender, EventArgs e)
  {
      ScriptManager.RegisterStartupScript(this, GetType(), "InvokeButton", "invokeButtonClick();", true);
  }
  
  protected void btnConfirm_Click(object sender, EventArgs e)
  {
     // save something in database
  }
  </code></pre>
  
  <p>But then the page postback before my btnConfirm_Click function get called...</p>
  
  <p>Thanks,</p>
  
  <p>Michael</p>