Question Passing variable to another sub routine

NewbieUK

New member
Joined
Jul 25, 2023
Messages
4
Programming Experience
Beginner
Good afternoon,
Please be gentle, i'm only a begineer at coding!
I have the following sub routine which extracts information from a datagrid. It's only 2 columns so quite simple.
The variable which is passed to the sub "SaveREGtxt(reg)" needs to be available outside of the below sub routine and into a "Button click sub routine."

VB.NET:
Public Sub GetCurrent()
    Dim pos As Integer = BS.Position
    Dim tz As String = dt(pos)(0)
    Dim reg As String = dt(pos)(1)
    SaveTZtxt(tz)
    SaveREGtxt(reg)
End Sub

Public Sub SaveREGtxt(s As String)
    Using sr As New IO.StreamWriter(OutputRegionFile, False)
        Dim regionarea As String = s
        sr.WriteLine(s)
    End Using
End Sub

Public Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click

How can i achieve this please?
Thanks
Simon
 
Last edited by a moderator:
Firstly, the way you're getting the data is wrong. Presumably BS is a BindingSource and dt is a DataTable bound to it. The way you're doing it, you'd end up getting the wrong data if you were to filter or sort the data. Even if you get the right data though, you're still doing it wrong. You should be using the Current property of the BindingSource to get the item. In this case, that item will be a DataRowView. For your purposes, you can treat that the same as you would a DataRow. That means that you can get field values by column index, as you are, but you should use column names to better document your code. Those column indexes mean nothing to me and they'll mean nothing to you not long after you put this project down. If you use column names, it's clear exactly what columns you're using and, if you have used goodnames, exactly what they're for.
VB.NET:
Dim row = DirectCast(BS.Current, DataRowView)
Dim tz = CStr(row("tz"))
Dim reg = CStr(row("reg"))
 
The variable [...] needs to be available outside of the below sub routine
So declare the variable outside the method then. You answered your own question. If a variable needs to be accessible in multiple methods then it needs to be declared outside any of them, i.e. a member variable or field.
 
Hi @jmcilhinney

Really appreciate you replying.

The code that i've used was copied from another thread and to be fair it does do what i need, to a degree!

The references to TZ and reg are Timezone and region. When i select the timezone zone from a combi box then the relevant region is picked up from the datagrid.

When i put in a stop to test the code, the "s" (highlighted in yellow) populates with the correct region.

VB.NET:
Public Sub SaveREGtxt(s As String)
    Using sr As New IO.StreamWriter(OutputRegionFile, False)
        Dim regionarea As String = s
        sr.WriteLine(s)
    End Using
End Sub

I have declared this variable outside of this sub but guessing it's wrong. I put...

VB.NET:
Dim regionarea As String

Sorry for the stupid question. I am learning...

Thanks
Simon
 
Last edited by a moderator:
It's not really clear from your explanation or your code what you are trying to accomplish.

Your variable declaration is basically correct if it's not within a method, although it would be better to declare it explicitly Private rather than allowing the access level to be set implicitly. There's no indication in what you've posted that you're actually setting the variable anywhere though. If you don't put anything in, you can't get anything out. Also, here:
VB.NET:
Dim regionarea As String = s
sr.WriteLine(s)
you are assigning the value from the field to a local variable, but then you never use that local variable anywhere and you do use the field again. If you'd like us to help you achieve your aim, you have to explain what that aim is in detail, step by step.
 
Thanks for your reply and apologies if i'm not clear. I will try to explain with my code below

As the code below should show, when i select a timezone from the combo box it selects the relevant region and currently writes this to a single line on a text file. This being the line highlighted in orange.

I would like this Region to be populated further down the code where the text says regionarea in yellow. This is in a separate sub and where my simple struggles are.

VB.NET:
Dim BasePath As String = My.Computer.FileSystem.SpecialDirectories.Desktop
Dim SourceDataFileXML As String = IO.Path.Combine(BasePath, "c:\temp\TimeZonesAndRegions.xml")
Dim OutputZoneFile As String = IO.Path.Combine(BasePath, "c:\temp\TimeZone.txt")

'This line currently writes the region to a file, which i don't want to do
[COLOR=rgb(251, 160, 38)]Dim OutputRegionFile As String = IO.Path.Combine(BasePath, "c:\temp\Regions.xml")[/COLOR]

With dt
.Columns.Add("Zone", GetType(String))
.Columns.Add("Region", GetType(String))

If IO.File.Exists(SourceDataFileXML) Then .ReadXml(SourceDataFileXML)
End With

BS.DataSource = dt

DataGridView1.DataSource = BS
With ComboBox1
.DataSource = BS
.DisplayMember = "Zone"
.ValueMember = "Region"
.AutoCompleteMode = AutoCompleteMode.SuggestAppend
.DropDownStyle = ComboBoxStyle.DropDown
.AutoCompleteSource = AutoCompleteSource.ListItems
End With

ComboBox1.DataBindings.Add("text", BS, "Zone", True, DataSourceUpdateMode.OnValidation)
LblRegion.DataBindings.Add("text", BS, "Region", True, DataSourceUpdateMode.OnValidation)
AddHandler BS.PositionChanged, AddressOf GetCurrent
End Sub

Public Sub GetCurrent()
Dim pos As Integer = BS.Position
Dim tz As String = dt(pos)(0)
Dim reg As String = dt(pos)(1)

SaveTZtxt(tz)
SaveREGtxt(reg)

End Sub
Public Sub SaveTZtxt(s As String)
Using sr As New IO.StreamWriter(OutputZoneFile, False)
sr.WriteLine(s)
End Using
End Sub

Public Sub SaveREGtxt(s As String)
Using sr As New IO.StreamWriter(OutputRegionFile, False)
Dim regionarea As String = s
sr.WriteLine(s)
'MsgBox(regionarea)
End Using
End Sub

Public Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click

Dim timeZone As System.TimeZone = timeZone.CurrentTimeZone
Dim sString As String = ""
Dim newFile As System.IO.StreamWriter
Dim filepath As String = "c:\temp\test1.xml"
Using sr As New StreamReader("c:\temp\test.ini")
sString = sr.ReadToEnd()
Dim sSubString = sString.Substring(sString.LastIndexOf("|") + 1).Trim()
Dim tz = TZConvert.WindowsToIana(sSubString)
Dim tzr = TZConvert.GetIanaTimeZoneNamesByTerritory()
lblIANAtz.Text = (tz)
'Label2.Text = ("Timezone: " & sString)
' Label3.Text = ("Region: " & sString1)
System.IO.File.WriteAllText("c:\temp\test1.xml", "")
Dim writeFile As System.IO.TextWriter = New StreamWriter(filepath)
writeFile.WriteLine("<characteristic uuid=" & """bb5642fe-ad4b-456e-b2b6-0937556ba444"" type=" & """com.airwatch.android.androidwork.datetime"" target=" & """2"">")
writeFile.WriteLine("<parm name=" & """AutomaticTime"" value=" & """False"" />")
writeFile.WriteLine("<parm name=" & """DateTime"" value=" & """HTTP"" />")
writeFile.WriteLine("<parm name=" & """URL"" value=" & """http://10.44.xx.xx/timezone/timezone.xml"" />")
writeFile.WriteLine("<parm name=" & """SetTimeZone"" value=" & """True"" />")

' I would like to write the region into area that i've written "regionarea" below. At present it doesn't write anything!
writeFile.WriteLine("<parm name=" & """Region"" value=" & [COLOR=rgb(247, 218, 100)]regionarea[/COLOR] & " />")
writeFile.WriteLine("<parm name=" & """TimeZone"" value=" & tz & " />")
writeFile.WriteLine("<parm name=" & """AllowDateTimeChange"" value =" & """True""/>")
writeFile.WriteLine("<parm name=" & """EnablePeriodicSync"" value=" & """True"" />")
writeFile.WriteLine("<parm name=" & """SyncIntervalDays"" value=" & """1"" />")
writeFile.WriteLine("</characteristic>")
writeFile.Close()
writeFile = Nothing
Exit Sub
End Using


End Sub

Many thanks
Simon
 

Latest posts

Back
Top