0

i have this function :

Public Sub javaMsg(ByVal message As String)
    Dim sb As New System.Text.StringBuilder()

    sb.Append("<script type = 'text/javascript'>")

    sb.Append("window.onload=function(){")

    sb.Append("alert('")

    sb.Append(message)

    sb.Append("')};")

    sb.Append("</script>")

    Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "alert", sb.ToString())
End Sub

i need to put it in a vb class so i can be able to use it in all my pages but i'm getting an error on "Page.ClientScript" saying that "Reference to a non-shred member requires an object reference"

How can i solve this please :)

Thank you !

1 Answer 1

2

You could always just change it to;

Public Function javaMsg(ByVal message As String) As String

    Dim sb As New System.Text.StringBuilder()   
    sb.Append("window.onload=function(){")
    sb.Append("alert('")
    sb.Append(message)
    sb.Append("')};")

    return sb.ToString()

End Sub

Then on your page call;

Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "alert", javaMsg("Hello World"), true)

Notice that there is an overloaded RegisterClientScriptBlock which actually renders the script blocks for you.

This way your function can be in what ever class you want and will not break.

Alternatively, you can pass the current page as a reference to your method;

Public Sub javaMsg(ByRef page As System.Web.UI.Page, ByVal message As String)

    Dim sb As New System.Text.StringBuilder()   
    sb.Append("window.onload=function(){")
    sb.Append("alert('")
    sb.Append(message)
    sb.Append("')};")

    page.ClientScript.RegisterClientScriptBlock(page.GetType(), "alert", sb.ToString(), true)

End Sub

And on your page call;

'' C# does not allow you to pass the page as a Reference type. Not sure if VB.Net does or not
'' So creating a reference to it before passing it in
Dim refPage As System.Web.UI.Page = me.Page
ClassName.javaMsg(refPage, "Hello World")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.