VB.NET - Working with Multiple Forms - vb.net

I'm trying to make a login window and a main window. The problem is when I close the login form and show the main window, the whole program stops.
The login form:
Imports System.IO
Imports System.Text
Imports System.Net
Public Class frmLogin
Dim address As String = "http://puu.sh/jKJ**Zq/d613de****29.txt"
Dim client As WebClient = New WebClient()
Private Sub frmLogin_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'frmMain.Close()
End Sub
Private Sub frmLogin_Close(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.FormClosed
frmMain.Show()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If attemptLogin() Then
MsgBox("Login Successful")
Me.Close()
'frmMain.Show()
Else
MsgBox("Username or password is incorrect")
End If
End Sub
Private Function attemptLogin()
Dim reader As StreamReader = New StreamReader(client.OpenRead(address))
Dim line As String
Dim username As String
Dim password As String
line = reader.ReadLine()
Do While Not line Is Nothing
username = line.Split(":")(0)
password = line.Split(":")(1)
If (username = TextBox1.Text And password = TextBox2.Text) Then
Return True
End If
line = reader.ReadLine()
Loop
reader.Close()
client.Dispose()
Return False
End Function
Private Function Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim client As WebClient = New WebClient()
Dim reader As StreamReader = New StreamReader(client.OpenRead(address))
Dim line As String
line = reader.ReadLine
Do While Not line Is Nothing
line = reader.ReadLine()
Loop
reader.Close()
Dim writer As StreamWriter = New StreamWriter(client.OpenRead(address))
writer.Write(TextBox1.Text & ":" & TextBox2.Text)
writer.Close()
client.Dispose()
Return False
End Function
End Class
The Main Window:
Public Class frmMain
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
'frmMain.Close()
End Sub
Private Sub frmMain_closed(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.FormClosing
End Sub
End Class
I am fairly new to VB.NET so sorry about the lack of knowledge/ugly coding. I'm used to programming GUIs in Java.

You need to set your 'Shutdown mode' to 'When last form closes'.
You can find this setting by going to My project and then clicking on Application (the first tab).
You can then find the setting at the bottom.

Related

Using open file dialog and save file dialog with a list box in VB

I need to save things someone adds to a list and open a txt file putting it into a list box. When I open a txt file I only get one line of code and my attempts to save only produce empty txt files. Any help will be greatly appreciated. Here is my code:
Imports System.IO
Public Class Form1
Public Listed As String
Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
Dim AllText As String = "", LineOfText As String = ""
Dim StreamToDisplay As StreamReader
OpenFileDialog1.Filter = "Text files (*.txt)}|*.txt"
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
Try
StreamToDisplay = My.Computer.FileSystem.OpenTextFileReader(OpenFileDialog1.FileName)
Label1.Text = OpenFileDialog1.FileName
Do Until StreamToDisplay.EndOfStream
LineOfText = StreamToDisplay.ReadLine()
'AllText = AllText & LineOfText & vbCrLf
lstBox.Items.Add(Listed)
Loop
lstBox.Items.Add(AllText).ToString()
StreamToDisplay.Close()
CloseToolStripMenuItem.Enabled = True
OpenToolStripMenuItem.Enabled = False
Catch ex As Exception
MsgBox("An error occurred." & vbCrLf & ex.Message)
End Try
End If
End Sub
Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click
SaveFileDialog1.Filter = "Text files (*.txt)|*.txt"
If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
My.Computer.FileSystem.WriteAllText(SaveFileDialog1.FileName, lstBox.Items.ToString(), False)
End If
End Sub
Private Sub CloseToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CloseToolStripMenuItem.Click
lstBox.Items.Clear()
Label1.Text = ""
CloseToolStripMenuItem.Enabled = False
OpenToolStripMenuItem.Enabled = True
End Sub
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim Prompt As String = "Enter Items To Add Here"
Listed = InputBox(Prompt)
lstBox.Items.Add(Listed).ToString()
End Sub
Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemove.Click
With lstBox
.Items.Remove(.SelectedItem)
End With
End Sub
End Class
Here's a simple example that:
adds items to a ListBox
saves them to a file
loads them from a file and populates the ListBox with them
Code:
Imports System.IO
Public Class Form1
Private Sub ButtonAddItem_Click(sender As Object, e As EventArgs) Handles ButtonAddItem.Click
ListBox1.Items.Add(DateTime.Now.Ticks)
End Sub
Private Sub ButtonSave_Click(sender As Object, e As EventArgs) Handles ButtonSave.Click
If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
Using writer = New StreamWriter(SaveFileDialog1.FileName)
For Each o As Object In ListBox1.Items
writer.WriteLine(o)
Next
End Using
End If
End Sub
Private Sub ButtonLoad_Click(sender As Object, e As EventArgs) Handles ButtonLoad.Click
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
Dim lines = File.ReadAllLines(OpenFileDialog1.FileName)
ListBox1.Items.Clear()
ListBox1.Items.AddRange(lines)
End If
End Sub
End Class

Data substring not showing full value

My code should be showing 32 characters but it's only showing 7. This is the code I currently have:
Imports System.IO
Public Class Form1
Private Property sr As Object
Private Sub BrowseBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BrowseBtn.Click
OpenFileDialog.ShowDialog()
FilePathLabel.Text = OpenFileDialog.FileName
End Sub
Private Sub SearchBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SearchBtn.Click
Dim sr As StreamReader = New StreamReader(OpenFileDialog.FileName)
Dim data = sr.ReadToEnd()
Dim pos = data.IndexOfAny("LASTSAVE")
If pos >= 0 Then
End If
CatiaVersionLabel.Text = data.Substring(pos, 32)
End Sub
End Class
Not too sure why it's doing this as the text that needs to be found is there when I open it independently.

Resize UserControls in every instance of TabPage

This has been killing me for a couple of weeks now. I have a browser that I've made and it's using a TabControl. Every time the TabPage "+" is clicked, a new one is added. Each one of these TabPages has userControls (WebBrowser, Address Bar, Back Button, Forward Button, etc..). When the user resizes Form1, I want all userControls to fit to the TabPage/Form1.
Basically, I want my userControls to fit the current size of the Form but I can't figure it out. Right now, I have the TabControls working but that was done by simply using the Anchor property. That option isn't avialable for the UserControls. I manually anchored it programatically but it doesn't resize. It just sticks everything right in the middle with the smaller size....
here's the Code:
'THIS IS THE CODE FOR THE FORM
Imports System.IO
Public Class Form1
'The Global Variables
Dim theControls1 As New theControls
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
TabPage1.Controls.Add(theControls1)
theControls1.theBrowser.Navigate("http://google.com")
End Sub
Private Sub Form1_SizeChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.SizeChanged
'For Auto Sizing theControls to Form1
theControls1.Width = TabControl1.Width - 8
theControls1.Height = TabControl1.Height - 25
End Sub
Private Sub TabControl1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TabControl1.Click
'Add new tab with the same controls.
Dim theNewTab As New TabPage
Dim theOtherControls As New theControls
Dim theTabCounter As Integer = TabControl1.TabPages.Count
theOtherControls.AutoSize = True
theOtherControls.Width = TabControl1.Width
theOtherControls.Height = TabControl1.Height
theOtherControls.Anchor = AnchorStyles.Right & AnchorStyles.Left & AnchorStyles.Bottom & AnchorStyles.Top
Dim theSelectedTab As String = TabControl1.SelectedTab.Text
If theSelectedTab = "+" Then
TabControl1.TabPages.Insert(theTabCounter - 1, theNewTab)
theNewTab.Controls.Add(theOtherControls)
theControls1.theBrowser.Navigate("http://google.com")
theOtherControls.theBrowser.Navigate("http://google.com")
TabControl1.SelectTab(theTabCounter - 1)
End If
End Sub
End Class
'THIS IS THE CODE FOR THE USERCONTROLS
Imports System.IO
Imports System.Data.OleDb
Public Class theControls
'The History Database Connection String
Dim theHistoryDatabaseConn As New OleDbConnection
Private Sub ComboBox1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles theAddressBar.KeyDown
'Navigate to Webpage stated in theAddressBar
If e.KeyValue = Keys.Enter Then
theBrowser.Navigate(theAddressBar.Text)
e.SuppressKeyPress = True
End If
End Sub
Private Sub goForward_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles goForward.Click
theBrowser.GoForward()
End Sub
Private Sub goBack_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles goBack.Click
theBrowser.GoBack()
End Sub
Private Sub theBrowser_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles theBrowser.DocumentCompleted
'Set Tab Text to current web page and Address Bar
Form1.TabControl1.SelectedTab.Text = theBrowser.Url.Host.ToString
Me.theAddressBar.Text = Me.theBrowser.Url.AbsoluteUri.ToString
'Read the History
theHistoryDatabaseConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Marc Wilson\Documents\Visual Studio 2010\Projects\myBrowser\myBrowser\bin\Debug\TheHistoryDB.accdb"
theHistoryDatabaseConn.Open()
'Populate theAddressBar with the contents from the History
theAddressBar.Items.Clear()
Dim readTheHistory As String
Dim getTheHistory As OleDbCommand
readTheHistory = "SELECT [Host Name] FROM TheHistory"
getTheHistory = New OleDbCommand(readTheHistory, theHistoryDatabaseConn)
Dim theData As New OleDbDataAdapter(getTheHistory)
Dim theTable As New DataTable("TheHistory")
'theHistoryDatabaseConn.Open()
theData.Fill(theTable)
For Each row As DataRow In theTable.Rows
theAddressBar.Items.Add(row.Item("Host Name"))
Next
'Writes history to TheHistory Database (No Duplicates!)
If theAddressBar.Items.Contains(theBrowser.Url.Host.ToString) Then
Else
'Write The History
Dim writeTheHistory As OleDbCommand = New OleDbCommand("INSERT INTO TheHistory ([Host Name], [Absolute Path]) VALUES (theBrowser.URL.Host.ToString, theBrowser.URL.AbsoluteUri.ToString)", theHistoryDatabaseConn)
writeTheHistory.Parameters.Add("#Host Name", OleDbType.Char, 255).Value = theBrowser.Url.Host.ToString
writeTheHistory.Parameters.Add("#Absolute Path", OleDbType.Char, 255).Value = theBrowser.Url.AbsoluteUri.ToString
theHistoryDatabaseConn.Close()
theHistoryDatabaseConn.Open()
writeTheHistory.ExecuteNonQuery()
theHistoryDatabaseConn.Close()
End If
theHistoryDatabaseConn.Close()
End Sub
Private Sub theBrowser_ProgressChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserProgressChangedEventArgs) Handles theBrowser.ProgressChanged
'Status Bar Text
Label1.Text = theBrowser.StatusText.ToString
End Sub
Private Sub theAddressBar_SelectedValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles theAddressBar.SelectedValueChanged
Me.theBrowser.Navigate(Me.theAddressBar.Text)
End Sub
End Class
Whenever you create an instance of your UserControl, set its Dock() property to Fill:
Dim theOtherControls As New theControls
theOtherControls.Dock = DockStyle.Fill

How do you read a file and display in listbox in VB.NET?

I was trying to display data from file in a list saved on the hard drive by clicking on a button, however I'm not sure on haw to do it properly:
Private Sub btnListRecipes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnListRecipes.Click
Dim TextLine As String
If System.IO.File.Exists(Filename) = True Then
Dim RecipeReader As New System.IO.StreamReader(Filename)
Do While RecipeReader.Peek() <> -1
TextLine = TextLine & RecipeReader.ReadLine() & vbNewLine
Loop
lstRecipes.Text = TextLine.Text
Else
MsgBox("File Does Not Exist")
End If
End Sub
I would be really grateful for assistance :D
Private Sub btnListRecipes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnListRecipes.Click
Try
lstRecipes.AddRange(File.ReadAllLines(FileName))
Catch
MsgBox("Unable to read file")
End Try
End Sub
Use:
lstRecipes.Items.Add(TextLine.Text)
More specifically before it jumps to the next item in the list, so this would go right after your assignment of TextLine.
you can do this:
Imports System
Imports System.IO
Public Class Form1
Public Shared listTXT, listOfTxt, listOfTxtFile As New List(Of String)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim path As String = "C:\myDirectory\"
Dim parentinfo As New DirectoryInfo(path)
' Store Text file name in a list
For Each txtFile As FileSystemInfo In parentinfo.GetFileSystemInfos()
listTXT.Add(txtFile.Name)
Next
' Store Path of Text file in a list
For noOfTxtFile = 0 To listTXT.Count - 1
Dim pathOfFile As String = path & listTXT(noOfTxtFile)
listOfTxtFile.Add(pathOfFile)
Dim obj As System.IO.StreamReader
obj = System.IO.File.OpenText(pathOfFile)
While Not obj.EndOfStream
listOfTxt.Add(obj.ReadLine)
End While
Next
Dim lineOfTxt As Integer
Dim txt As String
For lineOfTxt = 0 To listOfTxt.Count - 1
txt = listOfTxt(lineOfTxt)
ListBox1.Items.Add(txt)
Next
End Sub
End Class

vb.net IO.StreamWriter only works in debug mode

It works perfectly in debug mode but it gives me 'The process cannot access the file because it is being used by another process' unhandled exception error when I run the built one and press the Save button(It loads but not saves after that).
Any advice, please.
Imports System.IO
Public Class DL1
Function DirExists(ByVal DirName As String) As Boolean
On Error GoTo ErrorHandler
DirExists = GetAttr(DirName) And vbDirectory
ErrorHandler:
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub LoadGlink_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoadGlink.Click
GlinkList.Items.Clear()
Dim fileReader As System.IO.StreamReader
fileReader = _
My.Computer.FileSystem.OpenTextFileReader("c:\Source\DL1\Glink.txt")
Dim mystring() As String = fileReader.ReadToEnd.Split(vbNewLine)
GlinkList.Items.AddRange(mystring)
fileReader.Close()
Me.Controls("Glinklist").Focus()
End Sub
Private Sub linktochrome_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles linktochrome.Click
If GlinkList.SelectedItem IsNot Nothing Then
' selected item is sglink
Dim sglink = GlinkList.SelectedItem.ToString
Process.Start("C:\Users\1\AppData\Local\Google\Chrome\Application\chrome.exe", sglink)
End If
Me.Controls("Glinklist").Focus()
End Sub
Private Sub movetofol_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles movetofol.Click
Dim strDir As String
strDir = "C:\Users\1\Downloads\Glink\" & "\" & SFoltext.Text
If DirExists(Trim(strDir)) = False Then
MkDir(Trim(strDir))
End If
For Each f As String In Sresult1.Items
Dim f_name As String = Path.GetFileName(f)
My.Computer.FileSystem.MoveFile(f, strDir & "\" & f_name)
Next
Sresult1.Items.Clear()
GlinkList.Items.Remove(GlinkList.SelectedItem)
End Sub
Private Sub ChecKDL_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChecKDL.Click
Sresult1.Items.Clear()
Dim fileList As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
fileList = My.Computer.FileSystem.GetFiles("C:\Users\1\Downloads\")
For Each foundFile As String In fileList
Sresult1.Items.Add(foundFile)
Next
End Sub
Private Sub Bsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Bsave.Click
Dim i As Integer
'Saves Glinklist
Dim path As String = System.IO.Path.Combine("c:\Source\DL1\", "Glink.txt")
Using fs As New System.IO.FileStream(path, IO.FileMode.Create)
Using w As IO.StreamWriter = New IO.StreamWriter(fs)
For i = 0 To GlinkList.Items.Count - 1
w.WriteLine(GlinkList.Items.Item(i))
Next
w.Close()
End Using
End Using
End Sub
Private Sub RMselec_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RMselec.Click
GlinkList.Items.Remove(GlinkList.SelectedItem)
Me.Controls("Glinklist").Focus()
End Sub
End Class
Not sure it this could be the answer, but I will post here because I can better format the code.
Let me know if this changes anything
Change your reading function to
Using fileReader = _
My.Computer.FileSystem.OpenTextFileReader("c:\Source\DL1\Glink.txt")
Dim mystring() = fileReader.ReadToEnd.Split(vbNewLine)
GlinkList.Items.AddRange(mystring)
End Using
Or simply
Dim mystring() = File.ReadAllLines()
GlinkList.Items.AddRange(mystring)
Usually this means a permission issue. Try running Visual Studio as admin to eliminate that possibility.