Link to home
Start Free TrialLog in
Avatar of damixa
damixaFlag for Denmark

asked on

Global database connection VB script

Hi

I have made a database connection (works great) :

<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.SQLClient" %>
Sub page_load
  Dim connection as New SQLConnection("Server=Server; Database= db; UID= admin; PWD=password;")

  connection.Open

  Dim query as String = "SELECT * FROM news ORDER BY ID DESC"
  Dim command as New SQLCommand(query, connection)

  Dim dataReader as SQLDataReader
  dataReader = command.ExecuteReader(CommandBehavior.CloseConnection)

  dataGrid.DataSource = dataReader
  dataGrid.DataBind()

  connection.Close()

end sub

how to make this a global function?
SOLUTION
Avatar of aki4u
aki4u

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of spdude
spdude

Hi
To make this a global function
Step1       Create a class library project and add this function to that project

Step 2      Compile the library and add the reference of  new DLL to your project


I would also suggest to store the connection string in web.config file
 
Hi damixa,
You can create a separate project (data access layer), class library in which you can use this method and expose other data-access methods as public module. Then you can add references to this library from all your other projects using the same database.
A good alternative would be to use the Data Access application block that you can easily find on internet.

Cheers!
or without decalring the Namespace...Like this:

    Public Class MyFunctions
        Public Shared Function TestString() As String
            Return "Hello"
        End Function
    End Class

and call your function like this:

Response.Write(MyFunction.TestString())
Avatar of damixa

ASKER

spdude:
Don’t know how to compile a class file…

aki4u:
gets an error, I think class1.vb needs to be imported in WebForm1.aspx
You need to create new class...in VS IDE right click on project(second one from top)->Add->Add Class
Follow my instructions and you'll be ok.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of damixa

ASKER

Name 'myFunction' is not declared.
Avatar of damixa

ASKER

dataGrid.DataSource = class1.myFunction()
Works..
But I don’t get any data returned
Avatar of damixa

ASKER

Finally it works....
It was a problem with my page_load… :)

The first problem was: I was using web matrix and .net 1.1.
I have found VS2005 web dev. Express 2005 (free version) much better

Thanks a lot!!