Sikander Hayyat
Sikander Hayyat

Reputation: 115

How to use class code of vb.net in asp.net

I'm having trouble with using my vb.net code in asp.net webpage.

<%@ Page  Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="WebForm1.aspx.vb" Inherits="Banking_Application.WebForm1" CodeFile="~/WebForm1.aspx.vb" %>

class name is WebForm1. I've written code in a separate file and I want to use it in page.

Like

<% Dim total As Integer
    Dim val As tests.WebForm1
    val = New tests.WebForm1
    total = val.TotalBranches()
    total.ToString()
%>

I'm new to vb.net and asp.net.

All suggestions are welcome.

Thanks!

Upvotes: 0

Views: 1378

Answers (2)

Banana
Banana

Reputation: 7483

Well first of all i need to clarify a few things for you:

in Asp.net, you can embed code in your aspx page using <% %> code block, or write it in a separate file and use it from there.

in your page declaration, you specify the code behind of your page using the CodeBehind= attribute, so if you want to place your code in WebForm1.vb, your page declaration should include CodeBehind="WebForm1.vb" .

  • note: CodeFile="~/WebForm1.aspx.vb" is not needed.

the structure of the code behind for you aspx page, should look like that:

Public Class WebForm1
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub
    Public Function test1()
        Return "test"
    End Function
End Class

and you can add more functions as needed. in the example above, i have added a function called test1 for the purpose of this example.

now, after you have created your code behind in the correct structure, you can call its methods from the aspx page as if it was the same page:

<% =test1()
%>

this will return "test" as specified by the function in code behind.
you do not need to instantiate the class.

Upvotes: 1

Louis van Tonder
Louis van Tonder

Reputation: 3710

I think you are missing what is happening with the mechanics of asp.net.

You either:

  • Write code directly in the aspx page (within the html)
  • Or, you wrtie code in the code behind page... your WebForm1.aspx.vb page. From the code behind page, you can access and manipulate the server controls that is on the aspx (html) side...

Upvotes: 0

Related Questions