Student Student - 1 year ago 85 Question

Calling a procedure from its non native form

Ok, so

  1. frmResult populates a ListView with various calculations

  2. frmMenu has an export button (see code below). Pressing this is supposed to export the data in the ListView to a txt file. Currently, this button does not work. It says, List View is undeclared - obviously because the code shown below is not 'seeing' data held in frmResult

Question – how do I call the procedures stored in frmResult so that frmMenu can 'see' it.

Public Sub btnExport_Click(sender As Object, e As EventArgs) Handles btnExport.Click
Dim fileSaved As Boolean
Dim filePath As String
Do Until fileSaved
'Request filename from user
Dim saveFile As String = InputBox("Enter a file name to save this message")
'Click Cancel to exit saving the work
If saveFile = "" Then Exit Sub
Dim docs As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
filePath = IO.Path.Combine(docs, "Visual Studio 2013\Projects", saveFile & ".txt")

fileSaved = True
If My.Computer.FileSystem.FileExists(filePath) Then
Dim msg As String = "File Already Exists. Do You Wish To Overwrite it?"
Dim style As MsgBoxStyle = MsgBoxStyle.YesNo Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Critical
fileSaved = (MsgBox(msg, style, "Warning") = MsgBoxResult.Yes)
End If

'the filePath String contains the path you want to save the file to.
Dim rtb As New RichTextBox
rtb.AppendText("Generation, Num Of Juveniles, Num of Adults, Num of Semiles, Total" & vbNewLine)
For Each saveitem As ListViewItem In ListView1.Items
saveitem.Text & ", " &
saveitem.SubItems(1).Text & ", " &
saveitem.SubItems(2).Text & ", " &
saveitem.SubItems(3).Text & ", " &
saveitem.SubItems(4).Text & vbNewLine)
rtb.SaveFile(filePath, RichTextBoxStreamType.PlainText)
End Sub

Answer Source

Is this what you mean?

Public Sub Init()
    '... (all the code)
End Sub

Private Sub Results_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Call Init()
End Sub

You can call Init() from every form load you want. Maybe you want to create a module and store there your methods.

By the way, you only use Function when your methods needs to return a value.

If your code uses elements of the form (or other objects not constant) you need to pass those to the method, like this:

Public Sub Init(myListView As ListView) 
End Sub

Private Sub Results_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Call Init(ListView1)
End Sub

You can add as many parameters as you need. You have to learn the basics before going ant further.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download