473,549 Members | 2,543 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Calling variable across subs


Still new to vb.net in VS2005 web developer...

What is the proper/standard way of doing the following - setting the value
of a variable in one sub and
calling it from another? E.g., as below. The code below draws an error as
indicated.
Surely there has to be a better way than to make xxx a session variable?

Thanks

Jeff

Sub test()
Dim xxx As Integer = 9
End Sub

Sub Test3()
label1.text = xxx <- x is not declared
End Sub


--
Posted via a free Usenet account from http://www.teranews.com

Apr 17 '07 #1
8 12608
You should call it as a Function.

Public Function xxx() as Integer

Dim i as Integer = 9

Return i

End Function

Sub Test3

label1.text = xxx

End Sub

"Jeff" <no**@nothingX. comwrote in message
news:46******** *************** @free.teranews. com...
>
Still new to vb.net in VS2005 web developer...

What is the proper/standard way of doing the following - setting the value
of a variable in one sub and
calling it from another? E.g., as below. The code below draws an error as
indicated.
Surely there has to be a better way than to make xxx a session variable?

Thanks

Jeff

Sub test()
Dim xxx As Integer = 9
End Sub

Sub Test3()
label1.text = xxx <- x is not declared
End Sub


--
Posted via a free Usenet account from http://www.teranews.com

Apr 17 '07 #2
You are attempting to access a variable that is out of scope. Scope has
three major categories:

1. Local: Persisted in the current sub routine you are in
2. Module: Persisted in the current class or module you are in
3. Global: Persisted throughout the application

There are finer deviations of setting scope for a variable, lets take a look
at the following code snippet

public module MainModule

'Make a global variable
global itemIteratorCou nt as integer

'Make a module variable
private sampleString as string

shared sub Main

'Make a local variable
dim iLoop as integer

for i as integer = 1 to 100
for j as integer = 1 to 100
'Take note that i is only available for the scope of this loop
iloop += iloop
itemIteratorCou nt +=1
makeString()
console.writeli ne sampleString
next j
'Take note that j is not avaiable, it has gone out of scope until the
next i
next i

end sub

private function makeString() as string
'i is not available here
'j is not available here
'iloop is not available here

'sampleString is available here
sampleString = System.Guid.New Guid.ToString(" N")

'itemIterator is available here
itemIteratorCou nt +=1

end function
End Module
Having said all of this, no one really wants us to use GLOBAL any more.
Instead you should set up a singleton instead to host global variables.

example:

public class GlobalValues
private shared pItemIterator as integer
shared public readonly property ItemIterator as Integer
get
return pItemIterator
end get
set (value as integer)
pItemIterator = value
end set
end property
end class

to access the itemiterator you simply call:

GlobalValues.It emIterator +=1

Application and Session values have their own scope and purpose as well.
There is also a psuedo scope known as caching.

Application values allow everyone user session to interact with shared
information

Session values are like the global or singleton values

Caching is a hybrid and can be used at either the Application or Session
level. Ideally, caching is used to minimize the load and roundtrips to the
backend resorces such as database and file servers.

"Jeff" <no**@nothingX. comwrote in message
news:46******** *************** @free.teranews. com...
>
Still new to vb.net in VS2005 web developer...

What is the proper/standard way of doing the following - setting the value
of a variable in one sub and
calling it from another? E.g., as below. The code below draws an error as
indicated.
Surely there has to be a better way than to make xxx a session variable?

Thanks

Jeff

Sub test()
Dim xxx As Integer = 9
End Sub

Sub Test3()
label1.text = xxx <- x is not declared
End Sub


--
Posted via a free Usenet account from http://www.teranews.com

Apr 17 '07 #3

"Earl" <br******@newsg roups.nospamwro te in message
news:eH******** ******@TK2MSFTN GP06.phx.gbl...
You should call it as a Function.

Public Function xxx() as Integer

Dim i as Integer = 9

Return i

End Function

Sub Test3

label1.text = xxx

End Sub
Thanks (both Amdrit and Earl). Reference the above, if I use the method
above and access xxx several times from several different subs and if the
value I'm placing into the variable is taken from a cell in a database, will
the database be accessed each time or is there some type of caching involved
where the db access actually occurs once?

In other words, is the above still a good strategy if instead of the simple
example: "Dim i as Integer = 9" i is assigned after a number of commands
that read from a database and then xxx is access multiple times from several
subs.

Jeff

--
Posted via a free Usenet account from http://www.teranews.com

Apr 17 '07 #4
If I understand your question properly, this is a major reason variables
exist. They hold onto information in memory for as long as you need it.

Typically, you will want to minimize impact on your database. To do so, you
would read the data into variables, then work with the data, and finally
commit any changes back to the database.

Here is some sample code for you to browse and understand a little better.
This is a high stripped down set of code, and is not intended to be the only
approach when working with data. (I appologize to everyone on slow
connections, the code example is kinda long.)

Public Class SomeForm
'psuedo class to represent a form
' only the require portions of the form
' code logic are represented.

'Assume a datagrid to list multiple rows of data
' two text boxes to be bound to a single instance of data
' a button to save the data

Private Sub BindDataList()

Dim objList As System.Collecti ons.Generic.Lis t(Of GlobalData.myDa ta)
'Clean up our datagrid, incase are refreshing the list
Me.dbgData.data Source = Nothing
Me.dbgData.Tabl eStyles.Clear()

'Read the data in
objList = GlobalData.Data list("somefilte r")

'Bind it to our datagrid
Me.dbgData.data Source = objList

'Optionally set up tablestyles for the datagrid
'Code ommitted

End Sub

Private Sub BindDataItem()

'This would be called each time a row is clicked on the datagrid
Dim objDataList As System.Collecti ons.Generic.Lis t(Of
GlobalData.myDa ta)
Dim objData As GlobalData.myDa ta
'Clear any existing bindings that may be present
Me.txtValue1.da tabindings.clea r()
Me.txtValue2.da tabindings.clea r()

'Get the list the datagrid is bound to
objDataList = CType(Me.dbgDat a.datasource, ListBox(Of mydata))

'Get the selected row
objData = CType(objDataLi st(Me.dbgData.C urrentRowIndex) ,
GlobalData.myDa ta)

'Set this row to the current row
GlobalData.Load Data(objData)

Dim b As DataBinding

'bind value1
b = New DataBinding("Te xt", objData, "Value1")
Me.txtValue1.Da tabindings.Add( b)

'bind value2
b = New DataBinding("Te xt", objData, "Value2")
Me.txtValue2.Da tabindings.Add( b)

End Sub

Private Sub btnSave_Click(B yVal sender, ByVal e) Handles btnSave.Click
GlobalData.Save Data()
End Sub

End Class
Public Class GlobalData
Private Shared pstrConnectionS tring As String
Private Shared pobjCurrentData As myData

Shared Sub New()
'Initialize our connectionstrin g
pstrConnectionS tring = "ConnectionInfo Here"
End Sub

''' <summary>
''' Load on piece of data into memory
''' </summary>
''' <param name="filter"></param>
''' <remarks>The filter would ideally reference a unique column in the
database to return one row of data.</remarks>
Public Shared Sub LoadData(ByVal filter As String)
'Using filter information, load your data
'My example will just hardcode the values
pobjCurrentData = New myData
With pobjCurrentData
.Value1 = "Value1"
.Value2 = "Value2"
End With

End Sub

''' <summary>
''' Load one piece of data into memory
''' </summary>
''' <param name="dataObjec t"></param>
''' <remarks>Use this method if you have a list of data myData
objects.</remarks>
Public Shared Sub LoadData(ByVal dataObject As myData)
pobjCurrentData = dataObject
End Sub

''' <summary>
''' This is the target row of data that we are working with.
''' </summary>
''' <value></value>
''' <remarks></remarks>
Public Shared ReadOnly Property CurrentData() As myData
Get
Return pobjCurrentData
End Get
End Property

''' <summary>
''' Here we would save the data back to the database
''' </summary>
''' <remarks></remarks>
Public Shared Sub SaveData()
'Check if there are changes to worry about
If CurrentData.Has Changes Then
'Save the data
' database call is ommitted here
End If
End Sub

''' <summary>
''' Unload the current data from memory
''' </summary>
''' <remarks>Boun d object may still have a reference to the data. That
is ok, since the only way to save it is in the SaveDataMethod</remarks>
Public Shared Sub UnloadData()
pobjCurrentData = Nothing
End Sub

''' <summary>
''' Simulate loading multiple rows of data from the database.
''' </summary>
''' <param name="filter"></param>
''' <returns></returns>
Public Shared Function Datalist(ByVal filter As String) As
System.Collecti ons.Generic.Lis t(Of myData)
'again, I will simulate loading from the database
Dim objReturn As System.Collecti ons.Generic.Lis t(Of myData)
objReturn = New System.Collecti ons.Generic.Lis t(Of myData)

For i As Integer = 1 To 25
Dim objMyData As myData
objMyData = New myData

With objMyData
.Value1 = System.Guid.New Guid.ToString(" N")
.Value2 = System.Guid.New Guid.ToString(" N")
End With

objReturn.Add(o bjMyData)

Next

Return objReturn

End Function

''' <summary>
''' This class represents one row of data
''' </summary>
''' <remarks></remarks>
Public Class myData

'Data values read in from the database
Private pobjDatabaseVal ue1 As String
Private pobjDatabaseVal ue2 As String

'Working set of data, a copy if you will
Private pobjCurrentValu e1 As String
Private pobjCurrentValu e2 As String

'Flags to determine is the data is null
Private pblnIsNullValue 1 As Boolean = True
Private pblnIsNullValue 2 As Boolean = True

Public Property Value1() As String
Get
'Test if our value is null, if so throw an exception
If pblnIsNullValue 1 Then Throw New
System.Data.Dat aException("Val ue1 is Null")

'Otherwise return the value
Return pobjCurrentValu e1
End Get
Set(ByVal value As String)
pobjCurrentValu e1 = value
pblnIsNullValue 1 = False
End Set
End Property

Public Property Value2() As String
Get
'Test if our value is null, if so throw an exception
If pblnIsNullValue 2 Then Throw New
System.Data.Dat aException("Val ue2 is Null")

'Otherwise return the value
Return pobjCurrentValu e2
End Get
Set(ByVal value As String)
pobjCurrentValu e2 = value
pblnIsNullValue 2 = False
End Set
End Property

Public ReadOnly Property IsValue1Null() As Boolean
Get
Return pblnIsNullValue 1
End Get
End Property

Public ReadOnly Property IsValue2Null() As Boolean
Get
Return pblnIsNullValue 2
End Get
End Property

Public Sub SetValue1Null()
Value1 = String.Empty
pblnIsNullValue 1 = True
End Sub

Public Sub SetValue2Null()
Value2 = String.Empty
pblnIsNullValue 2 = True
End Sub

Public ReadOnly Property HasChanges() As Boolean
Get
If pobjCurrentValu e1.CompareTo(po bjDatabaseValue 1) <0 Then
Return True
If pobjCurrentValu e2.CompareTo(po bjDatabaseValue 2) <0 Then
Return True
End Get
End Property

End Class

End Class


"Jeff" <no****@george. comwrote in message
news:46******** *************** @free.teranews. com...
>
"Earl" <br******@newsg roups.nospamwro te in message
news:eH******** ******@TK2MSFTN GP06.phx.gbl...
>You should call it as a Function.

Public Function xxx() as Integer

Dim i as Integer = 9

Return i

End Function

Sub Test3

label1.text = xxx

End Sub

Thanks (both Amdrit and Earl). Reference the above, if I use the method
above and access xxx several times from several different subs and if the
value I'm placing into the variable is taken from a cell in a database,
will the database be accessed each time or is there some type of caching
involved where the db access actually occurs once?

In other words, is the above still a good strategy if instead of the
simple example: "Dim i as Integer = 9" i is assigned after a number of
commands that read from a database and then xxx is access multiple times
from several subs.

Jeff

--
Posted via a free Usenet account from http://www.teranews.com

Apr 17 '07 #5
Yup, not too many people would use such a function with a "magic" number.
They would instead do as your intuition says, have the function pull the
value from a database, or perhaps the function would do some calculations
(maybe even based upon some other functions, which in turn might pull their
values from a database). Indeed the idea of reusability is right there at
the top of the heap when it comes to writing code, so ideally your funciton
would get maximum possible use from throughout your app.

But it sounds to me like you are interested in a function that caches the
data. The simplest way to handle it would be to widen your scope on the
variable used to contain the data locally. For example, if your function
pulled some number from the database, you might set a Private variable that
can be accessed within the class where it is needed. For more complex data
"holding" operations, you might use various containers such as datasets and
datatables.

Private TestInteger as Integer

'this Function might be in a separate class or the Module
Public Function xxx() as Integer

Dim i as Integer = GetFancyCalcFro mDb()
Return i

End Function

Sub SetVariableToHo ldState()

'now TestInteger will hold the state of xxx without the need to call it
again
'you might actually set this the first time you call it
TestInteger = xxx()

End Sub

Sub Test3

label1.text = TestInteger

End Sub

Sub Test4

label200.text = TestInteger

End Sub

"Jeff" <no****@george. comwrote in message
news:46******** *************** @free.teranews. com...
>
"Earl" <br******@newsg roups.nospamwro te in message
news:eH******** ******@TK2MSFTN GP06.phx.gbl...
>You should call it as a Function.

Public Function xxx() as Integer

Dim i as Integer = 9

Return i

End Function

Sub Test3

label1.text = xxx

End Sub

Thanks (both Amdrit and Earl). Reference the above, if I use the method
above and access xxx several times from several different subs and if the
value I'm placing into the variable is taken from a cell in a database,
will the database be accessed each time or is there some type of caching
involved where the db access actually occurs once?

In other words, is the above still a good strategy if instead of the
simple example: "Dim i as Integer = 9" i is assigned after a number of
commands that read from a database and then xxx is access multiple times
from several subs.

Jeff

--
Posted via a free Usenet account from http://www.teranews.com

Apr 17 '07 #6

"Earl" <br******@newsg roups.nospamwro te in message
news:OW******** ******@TK2MSFTN GP02.phx.gbl...
But it sounds to me like you are interested in a function that caches the
data. The simplest way to handle it would be to widen your scope on the
variable used to contain the data locally. For example, if your function
pulled some number from the database, you might set a Private variable

Ahh, that's exactly what I needed. I kept reading about the different
designations of scope and I skipped over 'private' because the name lead me
to believe that it was irrelevant to what I was after.

You understood perfectly. That solved the problem - and it was so easy.

Thanks

Jeff

--
Posted via a free Usenet account from http://www.teranews.com

Apr 17 '07 #7
After awhile you'll start thinking like this. It's sick, really sick ...
"now if I can widen the scope on my marketing ..." Glad the kickstart
helped.

"Jeff" <no****@george. comwrote in message
news:46******** *************** @free.teranews. com...
>
"Earl" <br******@newsg roups.nospamwro te in message
news:OW******** ******@TK2MSFTN GP02.phx.gbl...
>But it sounds to me like you are interested in a function that caches the
data. The simplest way to handle it would be to widen your scope on the
variable used to contain the data locally. For example, if your function
pulled some number from the database, you might set a Private variable


Ahh, that's exactly what I needed. I kept reading about the different
designations of scope and I skipped over 'private' because the name lead
me to believe that it was irrelevant to what I was after.

You understood perfectly. That solved the problem - and it was so easy.

Thanks

Jeff

--
Posted via a free Usenet account from http://www.teranews.com

Apr 18 '07 #8
The error is due to scope. You are trying to access an out of scope
variable. create it globally and then it can be accessible across subs.

with regards,
J.V.Ravichandra n
- http://www.geocities.com/
jvravichandran
- Or, just search on "J.V.Ravichandr an"
at http://www.Google.com

*** Sent via Developersdex http://www.developersdex.com ***
Apr 18 '07 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
1879
by: Steven Bethard | last post by:
I'm playing around with some threading stuff right now, and I'm having a little trouble calling a function from one thread that affects another. Here's my setup: py> import os, threading, time py> def write(file_in, input_lines): .... for line in input_lines: .... time.sleep(0.5) .... file_in.write(line) .... ...
2
1490
by: nakhi | last post by:
Hi, I declared a dataset outside any subs, then I fill the dataset with a tables in a Private Sub1, then I want to take the data out from the dataset in Sub2. like . sub2() datagrid.datasource=ds.tables("t").defautview datagrid.databind() end sub
1
3156
by: John | last post by:
Hi, I have a routine that sets some session variables and then redirects the user to another page in the same application/ same folder. ======= Session("MyName") = "Fredsmith" Response.Redirect("./AnewPage.aspx") ======= If I go, Response.Write(Session("MyName")) in the new page the session variable does not exist.
3
1684
by: BuddyWork | last post by:
I want to know what is the best design approach to update a variable across threads.
3
1973
by: Samuel R. Neff | last post by:
Is there any way to declare a static variable within a generic type definition and have that variable be shared across all constructed generic types? For example, how can I modify this code: private class C<T> { public static int Counter = 0; }
11
4492
by: isoquin | last post by:
Really, i've looked for the answer, but I must be missing some syntax somewhere... I have a popup calendar which is to be used across several forms. Each form will need the calendar to automatically enter the selected date into the designated textbox (this part works beautifully already) and then update the filter on a continuous form to...
9
1015
by: boho | last post by:
Hi I have a website which is accessed externally via one virtual root ( requires SSL) and internally via an other virtual root. Is there a simple way to share variable, ie something like Application("variable") across the roots? I have tried defining the variable in global.asax but run into access issues. /bo
2
3479
by: aruna.mysore | last post by:
Hi all, I have specific question about usage of extern. I want to share a single variable say int a; across multiple files. I would define it in file1.c as int a=0; int main() {
1
248
by: guddu | last post by:
Hi, I have to share a variable across two libraries. These libraries are build separately and share a common header file. I had tried this earlier using extern variable. That didn't help. Any ideas about this ?? Thanks and Regards, Vishal
0
7532
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7730
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7491
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7823
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5101
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3509
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3491
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1956
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1068
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.