0

In the webpage I'm building, I have a div that I need to have hidden by default, and for it to appear when the user clicks on a link button. This is the code for the link button and the following div:

    <asp:LinkButton runat="server" Text="Words & stuff go here"
        OnClientClick="button_Click"></asp:LinkButton>

    <div id="Calculator" runat="server" visible="false">
        //CODE GOES IN HERE 
    </div>

And here is the code in the cs file for the link button:

void button_Click(object sender, EventArgs e)
    {
        if (Calculator.Visible)
            Calculator.Visible = false;

        else if (!Calculator.Visible)
            Calculator.Visible = true;
    }

I have a breakpoint inside the code behind, and when I debug, the breakpoint is never reached, and I have no idea why.

vcsjones
  • 138,677
  • 31
  • 291
  • 286
Ashton
  • 81
  • 3
  • 11

3 Answers3

2

on client click is for client side events. You have to use onClick="button_Click" to make it work.

Ebad Masood
  • 2,389
  • 28
  • 46
1

OnClientClick expects that the button_Click event is defined in javascript on the page, not in C# in the code-behind.

See this.

Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
1

The OnClientClick property of an ASP .NET control references a client-side function, which means that it will attempt to call a JavaScript function.

You have two options to fix your code.

Option 1:
If you want the button to do a Postback and call your button_Click function in your .cs file, you could just change your button code to:

<asp:LinkButton runat="server" Text="Words & stuff go here" OnClick="button_Click"></asp:LinkButton>

Option 2:
If you wish to use OnClientClick, you could do something similar to the following (in your .aspx file):

<script type="text/javascript">
function button_Click() {
  var calculator_id = '<%= Calculator.ClientID %>';
  var calculator = document.getElementById(calculator_id);
  if (calculator.style.display == 'none') {
    calculator.style.display = 'block';
  } else {
    calculator.style.display = 'none';
  }
}
</script>
Community
  • 1
  • 1
Nate Pinchot
  • 3,288
  • 24
  • 35
  • Originally trying to use an OnClick event gave me an error when having the button_Click event in the code behind, but after putting it in th aspx file in a script tag, using the OnClick in place of the OnClientClick works perfectly, Thanks! – Ashton Feb 17 '12 at 19:22