views:

11007

answers:

9

Hi,

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).

+6  A: 

cmdMyButton.attributes.add("onclick", "alert('hello');")?

alexmac
+3  A: 

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;";
WebDude
The URL would need to be quoted.
Tomalak
good spot thanks! updated
WebDude
A: 

button.Attributes.Add("onclick", "javascript:fireLightBox()")

that's the C# but I think that the VB.NET would be pretty similar.

Ryan
correct, it's exactly the same for c# and vb
WebDude
A: 

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!

Ed Altorfer
A: 

Thanks guys!

All I need to do now is just get it fire the javascript...

Once again, thanks!

A: 

Hi, I need to Call Javascript from ASP.NET 1.1 button "click". If I use button.Attributes.Add("onclick", "javascript:....") then the code behind of button is not working. So I need to call and javascript but in the same time to run and the server side button code

A: 

hi all please write this code in the page load event of the asp.net then it will 100% work.

A: 

Nice. but how about if the intended control is found in GridView control?

Mrkhalid
A: 

C# .net code to call a button_click event code from a menu_item_click event of a scrolling menu on the aspx page.

Shweta