I wanted to do something like this:
<asp:Label ID="lblMyLabel" onclick="lblMyLabel_Click" runat="server">My Label</asp:Label>
I know that in Javascript I can do:
<span onclick="foo();">My Label</span>
So I'm wondering why I can't do that with a Label object.
You can do it in code in the page_load eg:
You can use Attributes to add onclick client side callback.
I didn't know you can do this on span tags, but if it works you can add 'onclick' by
lblMyLabel.Attributes.Add("onclick", "foo();");
But
foo();
would need to be a client side javascript function.System.Web.UI.WebControls.Label
does NOT have OnClick server event. You could look into using AJAX if you want server callback with example above.You could also use
LinkButton
like other say. You can make it not look like a link by using CSS, if it is just that underline you are concerned about.ASPX:
CSS:
Just to chime in on this issue, I used a label in my .aspx page that was only to be visible in my DataList Item template if there were child records in the dataset.
I added a onclick function to the label:
moreOptionsLabel.Attributes.Add("onclick", string.Format("toggle_visibility('{0}')", div.ClientID));
in my .cs file. It will now control a div tag in the .aspx page to show or hide the records - because the onclick points to a client side javascript function. Notice the div.ClientID, that makes this workable in a datalist.
As noted above - the span tag does indeed become functional with "onclick". And since the label control is rendered as a span after the page request, using the Addtribute.Add("onclick".... does work.
The result is show/hide functionality of data with out doing a postback. If you use the LinkButton, or simlar controls - the postback and page reload is unavoidable - unless you want to get into some Ajax stuff.
NOTE: the span tag won't look clickable unless you style it with an underline and hand cursor.
Credit to this idea comes from Will Asrari over at http://www.willasrari.com/blog/display-nested-repeaters-and-gridviews-asynchronously/000292.aspx
Your question doesn't specify if you mean to raise the click event on the server (VB or c#) or the client (javascript.) If you're looking for a server-side event you should use a link button with css that makes the link appear as a label. You can then use the link button's server-side click event. If you're looking for a client-side click event - just type it into your server control markup
asp:label id="MyLabel" runat="server" onclick="javascript:alert('hello');" Text="Click Me";
ASP.NET will emit additional attributes in the html markup that generates.