How to make a private sub go back to sub main() - vb.net

Ok so, I have all my program and what not, it's just I don't how to prevent it from quitting the program after the execution of a
private sub
Like for example, I have
Private Sub KeyList()
Console.WriteLine("1.) File - Opens a test file")
Console.WriteLine("2.) Update - Updates the program using an external .bat file")
Console.WriteLine("3.) Username - ReDo Your username")
Console.WriteLine("4.) Site - Starts your browser and leads you to our site :D")
Console.WriteLine("5.) PLUGIN_STRT_NOPROT - Starts the loaded plugin without layered protection, do not do this unless you know")
Console.WriteLine("what you are doing")
Console.WriteLine("6.) PLUGIN_STRT_PROT - Starts loaded plugin with protection, reccomended.")
Console.WriteLine("7.) API_Str_Rand - Creates a random API string that you can assign to a plugin.")
Console.WriteLine("8) DownloadDevKit - Downloads the developmental kit to create a plugin")
End Sub
but after I hit any other key, the program terminates. How do I prevent the program from terminating, and going back to the
sub main()
Here is my data code for the entire program, it's VB.net 2010.
Module Module1
Sub Main()
REM Add all the Dimensions/Descriptions here.
Dim VersionName As String = "1"
Dim Action As String = "Action"
Dim username As String = "UserName"
REM The Visual part of the program. No pun intended :>
REM Ask the name for the session.
username:
Console.WriteLine("Hello, What is your name? ")
username = Console.ReadLine()
Console.WriteLine("Hello " + username)
If username = "Skycoder" Then
Console.WriteLine("Welcome back!, Planned updates to include in this are, 1.) ADd in more key features")
Console.WriteLine("2.) Add hotkeys")
Console.WriteLine("3.) Implement and auto updater")
Console.Beep()
If username = "" Then
Console.WriteLine("Please type in name. Numerals can be used")
GoTo username
End If
End If
Fish:
Console.ReadLine()
Console.Clear()
Console.Title = ("Desktop TBI | Hello " + username)
Console.WriteLine("-----------------------------------------------------------------------------------------------------------")
Console.WriteLine("Please select an option, note that this is a work in progress, and will contain more features in the future")
Console.WriteLine("")
Console.WriteLine(" Type 'File' to create the directory (Important if you want to add plugins)")
Console.WriteLine(" Using Version: " + VersionName)
Console.WriteLine("-----------------------------------------------------------------------------------------------------------")
Console.WriteLine(" Please choose what action you want to do")
Console.WriteLine(" Type in 'File' To find the directory")
Console.WriteLine(" Type in 'Update' To open the .bat file to download the updates")
Console.WriteLine("-----------------------------------------------------------------------------------------------------------")
Console.WriteLine("To create the new path, enter 'CreateDir'")
REM Begin the part where users can select their code.
Dim selection As String = Console.ReadLine
Select Case selection
REM This allows the creation of a text file.
Case "File"
Console.Clear()
File() REM Private sub selection
REM Updates their program.
Case "Username"
Console.Clear()
GoTo UserName
REM Set's their username for the program.
Case "Update"
Update()
Case "KeyList"
KeyList()
Case "CreateDir"
CreateDir()
Case "SERV_Start"
Chat_Start_SERV()
Case "Site"
Site()
Console.ReadLine()
End Select
End Sub
but after I select the case that I want to use and head into the sub code for the
keylists, it just terminates, and it doesn't even wait for me to read it. I'll literally provide video of it happening if it helps anyone... I am desperate...

Put your Select case block in the loop, add one more option ("Exit" for example) - if that option will be selected exit loop and application will be exited.
Console.WriteLine("0) Exit - Exit application")
Dim selection As String = Console.ReadLine()
While selection.Equals("Exit") = false
Select Case selection
REM This allows the creation of a text file.
Case "File"
Console.Clear()
File() REM Private sub selection
'...
'... other Case values
'...
End Select
selection = Console.ReadLine()
Loop

This application will only hit the Console.ReadLine() if the user entered "Site". Move the Readline statement below the End Select statement and it will do what you want.

Related

Trying to write files on multiple lines

i am trying to have variables linked to together like this: (login,pass,name) i want to have several line of those but whenever i register it clears the file help would be appreciated thanks.
Private Sub btn_register_Click(sender As Object, e As EventArgs) Handles btn_register.Click
Dim newline As String
Dim anything As String
password = txt_passwordregister.Text
username = txt_usernameregister.Text
If password <> "" And username <> "" Then
If validatepass() = False Then
MsgBox("please enter more than 8 characters")
Else
newline = txt_usernameregister.Text & "," & txt_passwordregister.Text
If rad_student.Checked Then
anything = newline & "," & txt_fullname.Text
Student.WriteLine(anything)
Student.Close()
Else
End If
MsgBox("You are now registered!")
End If
End If
End Sub
You might want to specify what kind of file you are talking to.
but since you don't actually indicate something in particular, here i used StreamWriter to append lines of text to a file.
Using studentWriter As StreamWriter = New StreamWriter("(<path>\<filename>.<txt>)", True)
studentWriter.WriteLine(anything)
End Using
sorry for my bad english.
You didnt show what's happening with the object Student before..
We assume you are using StreamWriter here??
Our best guess is that you open the file in new file mode rather than append mode..
To enable Append mode, provide the parameter when you create the Student object like this :
Dim Student as New StreamWriter("[File Location]",[Append Mode])
When [Append Mode] is True it will append the file and write after the last line you've written into it before.
When [Append Mode] is False it will treat the file as a new file and all the content inside will be lost.

Writing to .csv

I have written a basic console application and I want to write the data entered to a .csv file
When I enter test data the execution of the module is fine but it does not write to the .csv
I am trying to create an automated test data generation and this is my first attempt at vb by writing to .csv.
I want the code to pop up an input screen where data is input and written to a.csv file , the pop up is fine but the .csv is blank
Code. I have:
Module Module1
Dim objFile As New System.IO.StreamWriter("C:\Users\User\Documents\test.csv.csv", True)
Sub Main()
Console.WriteLine("what is your name")
Console.ReadLine()
Console.WriteLine("What is your Age")
Console.ReadLine()
Console.WriteLine("What is your Your Group")
Console.ReadLine()
End Sub
End Module
Here is the code I believe you are looking for. There are some pretty basic concepts that you appear to be missing (like storing values in variables and accessing those variables later). This sample demonstrates how to perform the task you described, but isn't useful in any practical sense.
Module Module1
Sub Main()
Console.WriteLine("What is your name?")
Dim Name As String = Console.ReadLine()
Console.WriteLine("What is your age?")
Dim Age As String = Console.ReadLine()
Console.WriteLine("What is your group?")
Dim Group As String = Console.ReadLine()
Using sw As New System.IO.StreamWriter("c:\test\outputfile.csv")
sw.WriteLine(Name & "," & Age & "," & Group)
End Using
End Sub
End Module

breaking out of sub after if statement in vb.net

I am trying to write code that opens the saveFileDialog only if the variable 'file' is not empty and generates an error message if 'file' is empty. The following code will pop up a error message box when 'file' is empty but will proceed to open the saveFileDialog anyway.
Public Shared Sub DownloadFile(cloudId As CloudIdentity, directoryPath As String, file As String)
Try
Dim cloudFilesProvider = New CloudFilesProvider(cloudId)
If file = "" Then
cloudFilesProvider.GetObjectSaveToFile("EstherTest", directoryPath, file)
End If
Catch
If file = "" Then
MessageBox.Show("Please select file to view")
End If
End Try
End Sub
Can you please direct me.
I think you have the wrong equality operator in your first if-statement.
In humand words, you are telling the compiler:
If file is equal to "" then do ... (If file = "" Then)
What you are trying to say is: if file is NOT equal to "" (If file <> "" Then).
As a second note: Unless an exception occurs, your second if statement will never be called, because the catch block will never be reached. You should put the second clause in a else or else if clause.
I've removed the try catch block for simplicity (and because I'm not really good at the vb.net syntax).
All in all your code should look like this:
Public Shared Sub DownloadFile(cloudId As CloudIdentity, directoryPath As String, file As String)
Dim cloudFilesProvider = New CloudFilesProvider(cloudId)
' if file is not emtpy, proceed
If file <> "" Then
cloudFilesProvider.GetObjectSaveToFile("EstherTest", directoryPath, file)
' else if file is empty, show message box
else if file = "" Then
MessageBox.Show("Please select file to view")
End If
End Sub

How to close parent form and open child?

Hey guys before I was just hiding the parent form, but now when I try to read from the parent file it says it can't because it's already running in a process. I followed some tutorial and it said to go to the project properties and have the application stop running when all the forms are closed.
But now since I did that it says the directory can't be found probably because I am reading the input from the parent form. Anyways here is my code
Dim writeFile1 As StreamWriter = New StreamWriter(File.OpenWrite("C:\Users\Nick\Documents\Visual Studio 2010\Projects\LoginFixed\Accounts\" + frmLogin.txtUser.Text))
How should I go about doing this?
Edit:
Private Sub btnHunter_Click(sender As System.Object, e As System.EventArgs) Handles btnHunter.Click
selection = "Hunter"
writeData.classSelection()
End Sub
This is what I have when the button is clicked.
Here is the classSelection sub:
Public Sub classSelection()
If frmClass.selection = "Hunter" Then
writeFile1.WriteLine(frmClass.selection)
End If
If frmClass.selection = "Gatherer" Then
writeFile1.WriteLine(frmClass.selection)
End If
If frmClass.selection = "Farmer" Then
writeFile1.WriteLine(frmClass.selection)
End If
writeFile1.Close()
End Sub
The error points to this line:
If frmClass.selection = "Hunter" Then
Saying part of the file path cannot be found.
If you want to read input textbox in closed parent form, you have to declare public var
Make a new module in your project .. and add this
public sLogin as String
And before you hide or close frmLogin .. add this
sLogin = txtUser.Text
So, you could change your code with
Dim writeFile1 As StreamWriter = New StreamWriter(File.OpenWrite("C:\Users\Nick\Documents\Visual Studio 2010\Projects\LoginFixed\Accounts\" & sLogin))
matzone has given you a good hint. And to check exactly what your path is, just add a MessageBox using variables :
Dim writePath1 As String
Dim writeFile1 As StreamWriter
writePath1 = "C:\Users\Nick\Documents\Visual Studio 2010\Projects\LoginFixed\Accounts\" & sLogin
If MessageBox.Show(writePath1, "Continue ?", MessageBoxButtons.YesNo) = DialogResult.Yes Then
writeFile1 = New StreamWriter(File.OpenWrite(writePath1))
' ...
writeFile1.Close() ' Very important ! Adrian pointed it out.
End If
^^ and if it works, you can discard the Dialog test or replace it by some test code like If File.Exists(...)
However, I don't understand wether you want to close the parent Form or hide it. It's different !
Closing the parent Form will discard any access to parent Form members, including txtUser.Text.
If you want to close the parent Form, the ChildForm should not be a child of that parent you are trying to close, or you must just hide the parent Form :
frmLogin.Hide() ' Not frmLogin.Close()
If you close frmLogin, frmLogin.txtUser won't be accessible, or use sLogin provided by matzone instead. Alternatively, you should pass frmLogin.txtUser.Text value to a custom property of ChildForm.
Imports System.IO
Public Partial Class ChildForm1
' Inherits System.Windows.Form
' ...
Private _txtUserFile As String
Public WriteOnly Property TxtUserFile() As String
Set(ByVal NewFileName As String)
_txtUserFile = NewFileName
End Set
End Property
Public Sub LoadFile()
Dim writeFile1 As StreamWriter = New StreamWriter(File.OpenWrite("C:\Users\Nick\Documents\Visual Studio 2010\Projects\LoginFixed\Accounts\" & txtUserFile))
' ...
writeFile1.Close()
End sub
' ...
End Class
Then use this in parent Form :
MyChildForm.TxtUserFile = Me.txtUser.Text
' Me.Close() ' This will definately KILL Form1 (the parent one)
Me.Hide() ' Always use Hide() until you'll terminate your Application
MyChildForm.Show()
MyChildForm.LoadFile()
^^ but this is not a good code either ! Your problem remains unclear (at least for me)
"Still saying it can't find part of the path", then check the path..
Does the file actually exists ?
Does the path contains glitch ? (use the provided MessageBox test)
Does your account can access that directory ? (Windows configuration and account levels)
Well !
In fact, the problem could be somewhere else.
For example, I was able to reproduce your exception by providing an empty string [""] as the value of, either :
frmLogin.txtUser.Text ' = ""
' or
sLogin ' = ""
' or
txtUserFile ' = ""
In fact, I get the "Could not find a part of the path..." exception because the StreamWriter couldn'd read/write to a File, as I didn't provided a valid FileName for that file. As the filename parameter was an empty string "", the provided path for StreamWriter was just representing a directory instead of a file and an exception was raised.
Now, you should check wether you have a valid path before building a new instance of StreamWriter to get sure you are actually pointing to a File ?
Dim writeFile1 As StreamWriter
Dim MyEntirePath As String = "C:\Users\...\Accounts\" + frmLogin.txtUser.Text
MessageBox.Show(MyEntirePath) ' would be enough to be sure your path is correct
' Some test code here...
If everythingOK then ' create the StreamWriter...
writeFile1 = New StreamWriter(MyEntirePath)
' ...
' ...
Also, it's not a good idea to create your streamwriter, and use it in another part/method of your code. You never known if one day, you'll change your code, and forget to make the link between
Dim writeFile1 As StreamWriter = New StreamWriter(File.OpenWrite("C:\Users\Nick\Documents\Visual Studio 2010\Projects\LoginFixed\Accounts\" + frmLogin.txtUser.Text))
' plus
Private Sub btnHunter_Click(sender As System.Object, e As System.EventArgs)
...
End Sub
' plus
Public Sub classSelection()
...
writeFile1.Close()
End Sub
^^ too much "here and there"...
You'll obviously also get an exception if you try to click btnHunter twice.. I don't know what is the purpose of your code nor how it works, it looks like a game.. But I would use File.Exist(..) checks, create the file before, if none, and put that in a Try/Catch to check if I eventually don't have administrator rights to write to that directory. Otherwise, make a code that allow user to read/write files to a custom folder. Andalso, you have :
Application.StartupPath
^^ Very usefull, like :
Dim MyFilePath As String = Application.StartupPath + "\Datas\MyText.txt"
After two weeks of coding, I usually forget where I put those "C:\blabla.." or "D:\gnagna\" or what classes actually uses those absolute reference paths. I've dropped this way of getting directories long ago since the day I moved to Win7 on another computer and all such applications I developped using that approach was doomed...

VB.NET Have whole program loop until user decides to exit?

I have a simple program to average ten (user-defined) numbers and then print the result. At the end of the program I'd like to print Would you like to average a new set of numbers? (Y/N) If the user inputs y than I want the program to execute again from the top. If the user inputs n than the program should close. I've tried researching this, but only found ways to have the entire console exit and re-open which is not what I want.
To detect what the user has entered you have a couple options:
Console.ReadKey()
will read the next keystroke. You can then use a simple Select Case branch to choose what to do.
You can also use:
Console.ReadLine()
which will return a string (after the user presses enter). You can then use a simple If statement to determine what's in the string (and repeat the query if something other than "y" or "n" was entered.)
Example:
Shared Sub Main()
While True
AverageNums()
Console.WriteLine( "Do you want to run again? (Y/N)" )
Dim key = Console.ReadKey()
If key.Key = ConsoleKey.N Then
Exit While
End If
End While
End Sub
Shared Sub AverageNums()
' ...
End Sub
My response may be a little late in the game, but thought I'd share a compact version implementing a try-catch method.
Sub Main()
Do
Try
Console.Write("Enter a value: ")
Console.ReadLine()
'...
SomeProcedure()
Catch ex As Exception
Console.WriteLine(ex.ToString)
Finally
Console.Write("Enter another value? (N for No) ")
End Try
Loop Until Console.ReadLine() = "N"
End Sub
Sub SomeProcedure()
'...
End Sub