tags:

views:

163

answers:

2

I have a button:

<button type="submit" class="contact" onclick="click">

and I have a c# code behind function:

protected void click(object sender, EventArgs e)
{
    contact_label.Text = "tester";
}

and there is a label on my page:

<asp:Label id="contact_label"...

The trouble is when I click the button the 'click' function is not being called, why not? How do I remedy it?

+6  A: 

you need a runat=server

try this:

<asp:button id="button" runat="server" onclick="click" cssclass="contact">

If you don't want to use the asp:button

<button id="button" runat="server" OnServerClick="click" >

Here is an article explaining it: http://ondotnet.com/pub/a/dotnet/2001/06/21/webforms.html?page=2

If you don't want to use a server side button at all, you could on the page_load event check which button did the submit action (through the request.form). You won't have an object to call the event handler, but you could but the code in another method and perform the same action.

Kevin
ah, you edited your a. meanwhile, good! You were quick ;-)
Abel
Thanks, I went with the OnServerClick event. The reason to why I am using a button rather than a asp:button is because of stylistic issues, as I am using images. Its not the best answer but it is part of 'what the client wanted' so I am going with that. thanks.
flavour404
That's what they invented `asp:ImageButton` for...
Abel
+1  A: 

You need a bit more then just runat="server", you need to:

  1. Choose to use an ASP.NET asp:Button class (as opposed to standard HTML)
  2. Add runat="server"
  3. Remove the non-relevant HTML code:

This is automatically also a submit button:

<asp:Button
     CssClass="contact" 
     runat="server" 
     OnClick="click" 
     Text="Hello World" />

C# will now be called:

protected void click(object sender, EventArgs e)
{
    contact_label.Text = "tester";
}

EDIT: Kevin showed how this can be done for default HTML controls and also explained how you can create additional "events" by using a switch-statement in your Page_Load. I misunderstood the question originally, I'll leave my answer for people wanting to work with ASP.NET controls.

Abel
That's the problem, I don't want to use an asp:button, is there a way to call the c# code without it?
flavour404
Why would you not want to use asp:button? You need a server side event handler. Which demands a server side control. As Kevin showed, you can use `OnServerClick` (apparently). Though I fail to see "why" you'd want to do something like that.
Abel
Its a stylistic method.
flavour404
+1 good explanation
Kevin