Reputation:
I have an ASP.NET page which pulls a set of images from a database table, and using an enumerator, goes through all of them and displays then.
This all happens in the codebehind (VB.NET), where the code adds the placeholder and some controls inside tables (tables inside the placeholder).
I've added a button to this placeholder (inside a table cell), all programatically, but how can I add a click event to the button programatically? I want to fire a javascript (lightbox) which shows a large preview of the image (this works when the user clicks a small image, which invokes a string hyperlink on the code that points to the javascript).
Upvotes: 4
Views: 51538
Reputation: 4371
The preferred method of the .NET Framework to add an attribute (e.g., onClick) to a webcontrol is:
control.Attributes.Add("onclick", "javascript:DoSomething('" + control.Value + "')")
You could also add the onClick event when another event is fired (e.g., DataBound):
Private Sub ctlControlName_ActionName(ByVal sender As Object, ByVal e As System.EventArgs)
Handles ctlControlName.ActionName
Dim control As ControlType = DirectCast(sender, ControlType)
control.Attributes.Add("onclick", "javascript:DoSomething('" + control.Value + "')")
End Sub
Hope this helps!
Upvotes: 2
Reputation: 6215
You can use the OnClientClick command to call client side javascript. If your button was called btnMyButton, write your code as follows:
btnMyButton.OnClientClick = "window.open('http://www.myimage.com'); return false;";
using return false at the end will ensure the button doesn't cause a post back on the page. replace the javascript with what you wanted to do.
An alternative to aboves would be
btnMyButton.Attributes.Add("onclick", "window.open('http://www.myimage.com'); return false;";
Upvotes: 7
Reputation: 9928
button.Attributes.Add("onclick", "javascript:fireLightBox()")
that's the C# but I think that the VB.NET would be pretty similar.
Upvotes: 1