Declaring variable publically

  • Thread starter Thread starter Microsoft
  • Start date Start date
M

Microsoft

I need to have two private subs have access to a variable. One will assign
the value and the second will use it.

The user will choose a file using the openfiledialog and a button

The user will use a second button to begin processing the file.

I can't seem to get the file name to move from sub to sub

First sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Browse.Click

Dim myStream As String

Dim filename As String

With findfile

..Title = "Pick file to open..."

..InitialDirectory() = "C:\"

..ShowDialog(Me)

End With

If findfile.ShowDialog() = DialogResult.OK Then

Dim FS As FileStream

FS = findfile.OpenFile

filename = FS.Name()

End If





Second sub which can'e see the filename variable and returns it as empty

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click

Stop

Dim subnet As String

Dim sr As StreamReader = New StreamReader(filename)

Dim line As String

'processing will occur here'
 
declare your filename variable at the class level. you don't need to declare
it as public. just declare it as private. this variable will be visible to
all the methods in the class.

eg:

class myclass
private sFileName as String

'all your subs here will be able to access the above variable.

end class

hope this helps..
Imran.
 
Hi,

You need to store the filename as a class variable.

In C# it would be something like

private string fname = "";

private void Button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();

ofd.Title = "Pick file to open..."

ofd.InitialDirectory = @"C:\";

if(ofd.ShowDialog() == DialogResult.OK)
{
fname = ofd.FileName;
}
}

private void Button2_Click(object sender, EventArgs e)
{
if(fname.Length == 0) // check if there is a filename
return;

StreamReader sr = new StreamReader(fname);
// processing here
}

fname has to be outside any method but inside the class scope.
 
Back
Top