Remember the old days of Classic ASP, when you could have one file, included on each page, which housed all your common functions? Well, it’s still possible today. But, instead of having an ‘Include’ file, today, in ASP.Net, you can create a Function Library, all in one file. Yes, includes are still possible in ASP.Net, in fact, simple, headers and footers are still a good a very clean and efficient way, in my opinion, to handle these. But, when it comes to common functions, referencing a Function Library on each page is the way to go.
Let’s start out by creating a clean, new file (save with .cs or .vb). Since this is a VB.Net example, we’ll call it ‘LIB.vb’. First, let’s Import a few namespaces (you’ll want to import whichever ones fit your needs). In our case, we’ll need these :
Imports System.Data Imports System.Data.SqlClient Imports System.Web.UI Imports System.Web.UI.WebControls
Then, let’s create our own Namespace, called ‘ASPNet101:
NameSpace ASPNet101 End Namespace
Inside that new namespace, on that page, we’ll create a new Class:
Public Class LB End Class
Now, let’s create several variables, inside that class that we’ll need to use:
Public Shared strConn as string = "server=YourServer;uid=YourUID;pwd=YourPWD;database=Your_DB" Public Shared MyConn as New SQLConnection(strConn) Public Shared MySQL as String Public Shared objDR as SqlDataReader
Now, since this a common function repository, we’ll include one function, to start out with, called ‘FillListBox’, and we’ll give it several arguments (Listbox, TblName, TblField, and TblID:
Public Shared Function FillListBox(LBName as ListBox, TblName as String, TblField as String, TblID as String) MySQL = "Select " & TblField & ", " & TblID & " from " & TblName MyConn.Open() Dim Cmd as New SQLCommand(MySQL, MyConn) objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection) lbName.DataSource = objDR lbName.DataTextField=TblField lbName.DataValueField=TblID lbName.DataBind() MyConn.Close() End Function
Click here, to see everything we have so far. Now, you’re probably asking, “But, how do I use it in my web page?” That’s no problem. In fact, that’s all that’s left to do in this tutorial. First, at the top of the page, let’s reference the ‘.vb’ file we just created:
<%@ Import Namespace="ASPNet101" %> <%@ Assembly src="LIB.vb" %>
Let’s create a Listbox on the page first, called ‘Listbox1′. Then, in the code section, we’ll reference populate the listbox with the Category Names from the Categories Table in the Northwind Database, using the code in the .vb file:
Continues…