分享
 
 
 

Creating Your Own Procedures

王朝asp·作者佚名  2006-01-10
窄屏简体版  字體: |||超大  

Creating Your Own Procedures

As you write Visual Basic .NET applications, you'll want to break your code

up into manageable "chunks." This shouldn't be a new concept to you, and it

should make sense. The larger the blocks of code you're working with, the

harder it is to debug, maintain, and manage the code. You've seen several

examples of this throughout this chapter already.

The building block of Visual Basic .NET code is the procedure. A procedure

has a beginning (a declaration), a middle (the code inside the procedure)

and an end (the End Sub statement, for example). As you'll see throughout

this book, there are a number of types of procedures, but for now, we'll

focus on Sub and Function procedures.

A Sub procedure is a block of code that includes code, takes some action,

but doesn't return a value. A Function procedure takes some action but

returns a single value. So far, you've seen event procedures—Sub

procedures that run in reaction to events on pages.

Why use procedures? Certainly, if you find that you're writing the same

lines of code in multiple places, you would want to create a procedure you

could call from all the places you would otherwise use the code and copy

that code into the new procedure.

If you double-click the Creating Procedures button on the VBLanguage.aspx

Web Form, it will lead you to the procedure shown in Listing 7.5.

Listing 7.5 Procedures Are Useful for Breaking Up Code into More Manageable

Chunks

Private Sub ProceduresSample()

Dim strConn As String

' Call a procedure that

' doesn't return a value.

InitControls()

' Call a Function to Return a Value

strConn = ConnectStringBuild("BJones", "password")

Response.Write("strConn = " & strConn & "<BR><BR>")

End Sub

The InitControls procedure is a simple Sub that takes an action (hiding a

control) and returns no value at all:

Private Sub InitControls()

' Demonstrate a procedure

' that doesn't return a value.

btnDataTypes.Visible = False

End Sub

The ConnectStringBuild procedure allows you to pass parameters, making it

possible to create generalized functionality. VB6 developers should note

that all parameters are passed by value in VB .NET, unless you specify

otherwise using the ByRef keyword. (This is the exact opposite of the way

VB6 works.) In addition, if you don't specify ByRef or ByVal, Visual Studio

.NET inserts the ByVal keyword for you. The ConnectStringBuild procedure

provides an example of this, allowing you to specify two parameters that

the procedure uses in creating an appropriate ADO.NET connection string:

Private Function ConnectStringBuild( _

ByVal LoginID As String, _

ByVal Password As String) As String

Return String.Format("Provider=sqloledb;" & _

"Data Source=(local);Initial Catalog=Northwind;" & _

"User ID={0};Password={1}", LoginID, Password)

End Function

Creating Classes

Creating your own classes allows you to encapsulate behavior in a reusable

fashion and allows you to provide the templates for creating multiple

instances of an object based on the template. That is, using classes, you

can create your own additions to the base class library provided by the

.NET Framework—every single object you use in your applications is based

on some class, created by some developer, describing the behavior of that

object.

The techniques for creating classes in VB .NET haven't changed much since

VB6, although you can now have more than one class per file. You still need

to create properties, methods, and possibly events. Methods and event

declarations have not changed much since VB6, but creating properties

requires a slightly different syntax.

As an example, we've provided the LoginInfo class, which provides LoginID,

Password, and DataSource properties, and the ConnectStringBuild method.

Double-click Creating Classes on the VBLanguage.aspx Web Form to find a

procedure that creates an object of the LoginInfo type. The definition for

this class also resides in the VBLanguage.aspx file, just below the end of

the Web Form's class. The code for this class is shown in Listing 7.6.

Listing 7.6 Classes Can Be Used to Group Data with Procedures That Interact

with That Data

Public Class LoginInfo

Private mstrLoginID As String

Private mstrPassword As String

Private mstrDataSource As String

Property LoginID() As String

Get

Return mstrLoginID

End Get

Set(ByVal Value As String)

mstrLoginID = Value

End Set

End Property

Property Password() As String

Get

Return mstrPassword

End Get

Set(ByVal Value As String)

mstrPassword = Value

End Set

End Property

Property DataSource() As String

Get

Return mstrDataSource

End Get

Set(ByVal Value As String)

mstrDataSource = Value

End Set

End Property

Public Function ConnectStringBuild() As String

Return String.Format("Provider=sqloledb;" & _

"Data Source=(local);Initial Catalog=Northwind;" & _

"User ID={0};Password={1}", Me.LoginID, Me.Password)

End Function

End Class

To use this class, you will declare a new instance of it, set the

properties you require, and then invoke the ConnectStringBuild method to

have it return the value. Listing 7.7 shows an example of creating and

using a class.

Listing 7.7 Using Your Own Class Is as Simple as Declaring a New Instance

of the Class

Private Sub ClassSample()

Dim oLogin As New LoginInfo()

With oLogin

.LoginID = "BJones"

.Password = "password"

.DataSource = "(local)"

Response.Write("ConnectString=" & _

.ConnectStringBuild() & "<BR>")

End With

End Sub

One problem with the LogInfo class, as it stands, is that you must create a

unique instance of the class each time you want to generate the connection

string. Sometimes, you may want to be able to call a method of a class

without needing to instantiate the object yourself. For example, when you

used the String.Format method, you didn't need to create a String object

variable, set it equal to a new String object, and then work with the

object. The String class provides the Format method (among many of its

methods) in a special way that allows the .NET Framework to instantiate an

object for you, as necessary. By adding the Shared keyword to a method, you

won't need to create an instance of the parent object before calling the

method—the .NET Framework will handle this for you.

We've provided a class, in DataHandler.vb, that we'll use throughout many

examples (and we'll expand the class as necessary). This class provides a

shared ConnectStringBuild method—you pass it user ID and password values,

and the method returns the appropriate connection string. The important

thing to remem-ber is that because the method is shared, you needn't create

an instance of the DataHandler class—simply call the method, and the .NET

Framework will do the work for you.

The following procedure, called when you click Classes with Shared Methods

on VBLanguage.aspx, calls the ConnectStringBuild method of the DataHandler

class. Note that the code never creates an instance of the DataHandler

class because the ConnectStringBuild method is shared. Here's the code:

Private Sub SharedMethodSample()

Dim strConn As String

strConn = _

DataHandler.ConnectStringBuild("Bjones", "Password")

Response.Write(strConn)

End Sub

The definition for the DataHandler class can be found in the DataHandler.vb

file within the VBLanguage.sln solution. This class looks like this:

Public Class DataHandler

Public Shared Function ConnectStringBuild( _

ByVal LoginID As String, _

ByVal Password As String) As String

Dim strConn As String

If LoginID = String.Empty Then

LoginID = "sa"

End If

strConn = String.Format("Provider=sqloledb;" & _

"Data Source=(local);Initial Catalog=Northwind;" & _

"User ID={0};Password={1}", LoginID, Password)

Return strConn

End Function

End Class

Applying What You Learned

Let's now take some of the techniques you have learned throughout this

chapter and apply them to the Northwind solution you are building. Follow

these steps to add a class that will be used throughout the rest of this

book:

Bring up your Northwind.sln file.

Set Option Strict to On.

Select the Project, Add Class menu item.

Set the class name to DataHandler.vb.

Add a shared method named ConnectStringBuild to this DataHandler class.

Re-create the code shown in the shared ConnectStringBuild method in this

chapter.

Bring up Main.aspx in the page designer.

Double-click the Logout LinkButton control and modify the lnkLogout_Click

procedure so it looks like this:

Private Sub lnkLogout_Click( _

ByVal sender As System.Object, _

ByVal e As System.EventArgs)

Session.Abandon()

Response.Redirect("Main.aspx")

End Sub

Open Login.aspx in the page designer.

Double-click the Login button and modify the btnLogin_Click procedure so

that it looks like this:

Private Sub btnLogin_Click( _

ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnLogin.Click

Session("LoginID") = "sa"

Session("Password") = ""

Server.Transfer("Main.aspx")

End Sub

For now, you will just set LoginID to "sa" so you can log in to your SQL

Server database.

Change the Page_Load procedure of Main.aspx to set the Visible property,

depending on whether Session("LoginID") is an empty string, as shown here:

Private Sub Page_Load(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles MyBase.Load

Dim blnShow As Boolean

blnShow = _

(Session("LoginID").ToString = String.Empty)

lnkLogout.Visible = blnShow

hypEmpMaint.Visible = blnShow

hypPwdChange.Visible = blnShow

End Sub

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有