Adding a click to a button to run javascript via VB.NET

I have an ASP.NET page that pulls a set of images from a database table and uses an enumerator, goes through all of them and displays.

All this happens in code (VB.NET), where the code adds a placeholder and some controls inside tables (tables inside a placeholder).

I added a button to this placeholder (inside a table cell), all programmatically, but how can I add a click event to a button programmatically? I want to run javascript (lightbox), which shows a large preview of the image (this works when the user clicks on a small image that calls a string hyperlink to the code pointing to javascript).

+4
source share
4 answers

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

+14
source

You can use the OnClientClick command to invoke client side javascript. If your button was called by btnMyButton, write your code as follows:

 btnMyButton.OnClientClick = "window.open('http://www.myimage.com'); return false;"; 

using return false at the end will ensure that the button does not lead to a message on the page. replace javascript with what you wanted to do.

An alternative to the aboves would be

 btnMyButton.Attributes.Add("onclick", "window.open('http://www.myimage.com'); return false;"; 
+7
source

The preferred .NET Framework method for adding an attribute (e.g. onClick) to the webcontrol is:

 control.Attributes.Add("onclick", "javascript:DoSomething('" + control.Value + "')") 

You can also add an 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!

+2
source

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

that C #, but I think VB.NET would be very similar.

+1
source

Source: https://habr.com/ru/post/1277614/


All Articles