How to Return Value from Module?

H

hailconan

Hi,
Suppose I have this code:
----------
Imports System.IO

Module Module1

Sub Main()
Dim TextFile As New StreamReader("c:\test.txt")

Dim Content As String

Do
Content = TextFile.ReadLine()

If (Content <> Nothing) Then
Console.WriteLine(Content)
End If
Loop While (Content <> Nothing)

TextFile.Close()
End Sub
End Module
--------


I have created Module1.vb

In the main Form I created Button & TextBox.

My problem:
How I can return Data from the Module1.vb to the TextBox ?
it is the first tim i am trying to use ind understand Modules :(

THX
 
M

Marina Levit [MVP]

A module is just a class. There is no concept of returning values with
classes.

Methods and properties can return values. So you can add a property or
method to your module, and have your form call it.
 
C

Cor Ligthert [MVP]

Hail,

A module makes it possible to share code by all other modules and instanced
classes (objects).
(For the rest it is the same as any other code)

Therefore I would never write it like you but do (although I trie forever to
avoid modules and use instanced classes (objects) ).

Module Module1
Public Function ReadMain(byval theFileName as string) as String
Dim TextFile As New StreamReader(theFileName)
...
...
Return Content
End Function
End module

Now you can use this everywhere in your program as

Dim myreadedcontent as string = Module1.ReadMain("c:\test.txt")

I hope this helps,

Cor
 
M

Marina Levit [MVP]

Are you saying you don't know how to write a method or property? In which
case you need to go back and read up before moving forward.

In your case, by the way, it doesn't look like you have a form or anything
like that. If this Sub Main is the main entry point of the application, then
the application ends as soon as this method completes. So the application is
done, I don't see what you are trying to do here.

Here is an example using your code. I modified it to have a function that
can return a string. Presumably, something else at some point is going to
call Module1.GetContent().

Module Module1

Public Function GetContext() As String
Dim TextFile As New StreamReader("c:\test.txt")

Dim Content As String

Do
Content = TextFile.ReadLine()

If (Content <> Nothing) Then
Console.WriteLine(Content)
End If
Loop While (Content <> Nothing)

TextFile.Close()

Return Content
End Sub
End Module
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top