when the text in a textbox is equal to a certain word i need to value in the combo box to be saved for that text - vb.net

I have orders in text files in the debug folder and when i type the name of the order in a text box it displays the order is a list box and there is a combo box underneath where i can change the status of the meal preparation (Being prepared, ready to deliver etc,). If i go back to that form and type in the same order name into the textbox i need to previous prepartion status to be already in the textbox. Thanks for any help!
Public Class frmOrderStatus
Private Sub btnStatus_Click(sender As Object, e As EventArgs) Handles btnStatus.Click
Dim sr As IO.StreamReader = IO.File.OpenText(strTxtOrderNum & ".txt")
Do Until sr.EndOfStream
lstOrder.Items.Add(sr.ReadLine)
Loop
End Sub
Private Sub OrderStatus_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lstOrder.Items.Clear()
btnStatus.Enabled = False
ChangeStatus.Enabled = False
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnValidate.Click
strTxtOrderNum = txtOrderNum2.Text
btnStatus.Enabled = True
ChangeStatus.Enabled = True
End Sub
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
strSaveStatus = ChangeStatus.SelectedIndex
End Sub
Private Sub ChangeStatus_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ChangeStatus.SelectedIndexChanged
End Sub
End Class

It recognizes the file; it just tells you it is in use. A Stream must be closed and disposed. I don't see the StreamReader even being closed let alone disposed. A `Using...End Using block will close and dispose of objects even if there is an error.
I just used a text file I happened to have to test.
Private strTxtOrderNum As String = "host"
Private Sub ReadFile()
Using sr As IO.StreamReader = IO.File.OpenText(strTxtOrderNum & ".txt")
Do Until sr.EndOfStream
ListBox1.Items.Add(sr.ReadLine)
Loop
End Using
End Sub
Private Sub WriteFile()
Dim strSelectedItem = ComboBox1.Text
Using swVar As IO.StreamWriter = IO.File.AppendText(strTxtOrderNum & ".txt")
swVar.WriteLine(strSelectedItem)
End Using
End Sub

Related

Saving and reading files on Visual basic

Hi I'm creating a "Toilet paper tracker" on visual basic and I'm struggling with saving and reading files, I know I am missing stuff. The user should be able to login and input a threshold and when reached a warning will pop up saying "buy more toilet paper" (i haven't coded this yet) and the user can add to create a total and subtract from it too. The user should also be able to save the total to a file and I want the program to be able to read the file and change the total if the user wants to add or subtract again. It would be greatly appreciated if you pointed me in the right direction, I'm only young so it's relatively simple. Here is my program :)
Imports System.IO
Public Class frmTPT
Private Sub TPT_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call loadchangetotal()
End Sub
Sub loadchangetotal()
cboChange.Items.Add("Add to Total")
cboChange.Items.Add("Subtract from Total")
End Sub
Private Sub cboVenue_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboChange.SelectedIndexChanged
If cboChange.Text = "Add to Total" Then
Dim frmChangeACopy As New frmChangeA
frmChangeACopy.Show()
Me.Hide()
ElseIf cboChange.Text = "Subtract from Total" Then
Dim frmChangeSCopy As New frmChangeS
frmChangeSCopy.Show()
Me.Hide()
End If
End Sub
Private Sub btnReturn_Click(sender As Object, e As EventArgs)
Dim frmLoginCopy As New frmLogin
frmLoginCopy.Show()
Me.Hide()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
txtThreshold.Text = ""
cboChange.Text = ""
txtTotal.Text = ""
End Sub
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
End
End Sub
Private Sub LogoutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LogoutToolStripMenuItem.Click
Dim frmLoginCopy As New frmLogin
frmLoginCopy.Show()
Me.Hide()
End Sub
Private Sub btnReadTotal_Click(sender As Object, e As EventArgs) Handles btnReadTotal.Click
Dim FileReader As StreamReader
Dim result As DialogResult
result = OpenFileDialog1.ShowDialog
If result = DialogResult.OK Then
FileReader = New StreamReader(OpenFileDialog1.Filename)
txtFileContent.Text = FileReader.ReadToEnd() 'i want to be able to read a
'previously saved total so that
FileReader.Close() 'it can be used to find the new total
'after it has been added to
End If 'or subtratced
End Sub
Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
Call SaveFile()
End Sub
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
Dim A, S, NewTotal As Integer
A = Val(frmChangeA.txtAdd.Text)
S = Val(frmChangeS.txtSubtract.Text)
NewTotal = A - S 'I want to be able to load a previously saved total if one exists and add and
'subtract from it
End Sub
End Class
Sub SaveFile()
Dim FileWriter As StreamWriter
Dim results As DialogResult
results = SaveFileDialog1.ShowDialog
If results = DialogResult.OK Then
FileWriter = New StreamWriter(SaveFileDialog1.FileName, False)
FileWriter.Write(txtFileContent.Text) ' is txtFileContent supposed to be
' the name of my textbox?
FileWriter.Close()
End If
End Sub
Design
You didn't mention if you were using .Net Core or 4.x. If the later, you can sometimes use the Insert Snippet functionality to learn how to do common tasks. For example in this case you could right click in the code editor and select Insert Snippet then Fundamentals then File System and finally Write text to a file. This will result in the following VB code:
My.Computer.FileSystem.WriteAllText("C:\Test.txt", "Text", True)
Unfortunately, this option doesn't work with .Net core since the My namespace wasn't ported to core.
The key point of this problem lies in reading and writing data from text. It is a clear idea to write two methods to achieve read and write.
You can refer to the following code. The two methods in the following example are WriteTotal(), ReadTotal().
Design:
Public Class Form1
Dim Oldtotal As Integer
Dim Newtotal As Integer
Private Sub btnLoadTotal_Click(sender As Object, e As EventArgs) Handles btnLoadTotal.Click
WriteTotal()
ReadTotal()
End Sub
Private Sub btnUpdateTotal_Click(sender As Object, e As EventArgs) Handles btnUpdateTotal.Click
cboChange.Text = Nothing
WriteTotal()
ReadTotal()
MsgBox("Inventory updated")
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cboChange.SelectedIndex = 0
ReadTotal()
End Sub
Sub WriteTotal()
Using swriter As IO.StreamWriter = New IO.StreamWriter("D:/paperstore.txt", False, System.Text.Encoding.UTF8)
If cboChange.Text = "Add to Total" Then
Newtotal = Oldtotal + CType(txtThreshold.Text, Integer)
swriter.WriteLine(Newtotal)
ElseIf cboChange.Text = "Subtract from Total" Then
If CType(txtThreshold.Text, Integer) > Oldtotal Then
swriter.WriteLine(Oldtotal)
MsgBox("buy more toilet paper")
Else
Newtotal = Oldtotal - CType(txtThreshold.Text, Integer)
swriter.WriteLine(Newtotal)
End If
Else
swriter.WriteLine(txtTotal.Text)
End If
End Using
End Sub
Sub ReadTotal()
Using sreader As IO.StreamReader = New IO.StreamReader("D:/paperstore.txt", System.Text.Encoding.UTF8)
Try
Oldtotal = sreader.ReadLine()
txtTotal.Text = Oldtotal
Catch ex As Exception
MsgBox(ex.Message)
End
End Try
End Using
End Sub
End Class

Shorten code vb.net

Is it possible to shorten these codes? If yes, how? Thanks for your answer guys.
Private Sub txtFirstName_GotFocus(sender As Object, e As EventArgs) Handles txtFirstName.GotFocus
lblFirstName.Visible = True
End Sub
Private Sub txtLastName_GotFocus(sender As Object, e As EventArgs) Handles txtLastName.GotFocus
lblLastName.Visible = True
End Sub
Private Sub txtMiddleName_GotFocus(sender As Object, e As EventArgs) Handles txtMiddleName.GotFocus
lblMiddleName.Visible = True
End Sub
Private Sub txtAddress_GotFocus(sender As Object, e As EventArgs) Handles txtAddress.GotFocus
lblAddress.Visible = True
End Sub
Private Sub txtContact_GotFocus(sender As Object, e As EventArgs) Handles txtContact.GotFocus
lblContact.Visible = True
End Sub
Since your labels and text boxes essentially have the same name (it's only the prefix that's different) you can:
Bind all GetFocus events to a single event handler.
Get the sender's name (sender is the control that raised the event), remove the txt prefix and replace it with lbl.
Look for a control by the new name (lbl...).
If found, make it visible.
In code it'd look like this:
Private Sub TextBoxes_GotFocus(sender As Object, e As EventArgs) Handles txtFirstName.GotFocus, txtLastName.GotFocus, txtMiddleName.GotFocus, txtAddress.GotFocus, txtContact.GotFocus
Const NamePrefix As String = "txt"
Const NewPrefix As String = "lbl"
Dim ctrl As Control = TryCast(sender, Control)
If ctrl IsNot Nothing AndAlso ctrl.Name.StartsWith(NamePrefix) Then 'Check if the sender's name starts with our prefix.
Dim NewName As String = NewPrefix & ctrl.Name.Remove(0, NamePrefix.Length) 'Remove the old prefix and replace it with the new one.
Dim Controls As Control() = Me.Controls.Find(NewName, True) 'Look for the control of our new name.
If Controls.Length > 0 Then 'Did we find one?
Controls(0).Visible = True 'Make it visible.
End If
End If
End Sub

opening files added to a combobox

Dim dir = "..//Football/"
Private Sub FTablebutton_Click(sender As Object, e As EventArgs) Handles FTablebutton.Click
For Each file As String In System.IO.Directory.GetFiles(dir)
FfilesComboBox.Items.Add(System.IO.Path.GetFileNameWithoutExtension(file))
Next
End Sub
Private Sub FfilesComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles FfilesComboBox.SelectedIndexChanged
Dim openfile As String = System.IO.Path.Combine(dir, FfilesComboBox.SelectedItem.ToString)
'start the process using the openfile string
Process.Start(openfile)
End Sub
I am able to add all the files to combobox but the problem is i cannot open the file when selected from the combobox
Try this
Private Sub FTablebutton_Click(sender As Object, e As EventArgs) Handles FTablebutton.Click
For Each file As String In System.IO.Directory.GetFiles(dir)
FfilesComboBox.DisplayMember = "key"
FfilesComboBox.ValueMember = "value"
FfilesComboBox.Items.Add(New DictionaryEntry(System.IO.Path.GetFileNameWithoutExtension(file), System.IO.Path.GetFileName(file)))
Next
End Sub
Private Sub FfilesComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles FfilesComboBox.SelectedIndexChanged
Dim openfile As String = System.IO.Path.Combine(dir, FfilesComboBox.SelectedItem.Value.ToString)
'start the process using the openfile string
Process.Start(openfile)
End Sub
If you Then use Visual studio 2008 or newer. you can use Anonymous class to store the full file path with the FileNameWithoutExtension.
Dim dir = "..//Football/"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
FfilesComboBox.DisplayMember = "Text"
End Sub
Private Sub FTablebutton_Click(sender As Object, e As EventArgs) Handles FTablebutton.Click
For Each file As String In System.IO.Directory.GetFiles(Dir)
FfilesComboBox.Items.Add(New With {.Text = System.IO.Path.GetFileNameWithoutExtension(file), .Value = file})
Next
End Sub
you can use ComboBox1.SelectedItem.Value to get the value (that is the file full path)
Private Sub FfilesComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles FfilesComboBox.SelectedIndexChanged
'start the process using the openfile string
Process.Start(FfilesComboBox.SelectedItem.Value)
End Sub
This will work even you choose to loop over sub directories.
This code is tested and worked fine

Open a ".exe" with a Button using a file path from a TextBox

I have a TextBox called TextBox1, which is filled by a Button that gets a file path using OpenFileDialog. I want a button (Button3) to start several processes one after another with an interval of 2 hours then close it and open the next one.
In total I have 4 different TextBoxes (TextBox1, TextBox2, TextBox3 and TextBox4) and 4 different file paths that I want to open with the same button with the interval I mentioned before.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
OpenFileDialog1.Title = "Please Select a File"
OpenFileDialog1.InitialDirectory = "C:temp"
OpenFileDialog1.ShowDialog()
End Sub
Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
Dim strm As System.IO.Stream
strm = OpenFileDialog1.OpenFile()
TextBox1.Text = OpenFileDialog1.FileName.ToString()
If Not (strm Is Nothing) Then
'insert code to read the file data
strm.Close()
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
OpenFileDialog2.Title = "Please Select a File"
OpenFileDialog2.InitialDirectory = "C:temp"
OpenFileDialog2.ShowDialog()
End Sub
Private Sub OpenFileDialog2_FileOk(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog2.FileOk
Dim strm As System.IO.Stream
strm = OpenFileDialog2.OpenFile()
TextBox3.Text = OpenFileDialog2.FileName.ToString()
If Not (strm Is Nothing) Then
'insert code to read the file data
strm.Close()
End If
End Sub
Private Sub TextBox3_TextChanged(sender As Object, e As EventArgs) Handles TextBox3.TextChanged
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
End Sub
End Class
To launch a new process use:
dim myProcess = Process.start(filename)
You dont' need the code that does the following:
Dim strm As System.IO.Stream
strm = OpenFileDialog2.OpenFile()
If Not (strm Is Nothing) Then
strm.Close()
End If
This is opening the exe file as if it were trying to read the data from it.
Instead just use
dim process = Process.Start(OpenFileDialogX.Filename)
Note: your initial directory seems to be c:temp not c:\temp as it probably should be

clear combobox text entered in text box portion

I created a simple program that reads and writes to an output file in the bin folder, it works almost perfect. btnRemove deletes the selected item in cboFriends(which is good). However, I also need btnRemove to delete text entered in the text box portion. How do i do this? I apologize in advance for the basicness of the question.
Public Class frmMain
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub frmMain_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
Dim outFile As IO.StreamWriter
outFile = IO.File.CreateText("MyFriends.txt")
For intIndex As Integer = 0 To cboFriends.Items.Count - 1
outFile.WriteLine(cboFriends.Items(intIndex))
Next intIndex
outFile.Close()
End Sub
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim inFile As IO.StreamReader
Dim strInfo As String
If IO.File.Exists("MyFriends.txt") Then
inFile = IO.File.OpenText("MyFriends.txt")
Do Until inFile.Peek = -1
strInfo = inFile.ReadLine
cboFriends.Items.Add(strInfo)
Loop
inFile.Close()
End If
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
If cboFriends.Items.Contains(cboFriends.Text) Then
Else
cboFriends.Items.Add(cboFriends.Text())
End If
End Sub
Private Sub btnRemove_Click(sender As Object, e As EventArgs) Handles btnRemove.Click
cboFriends.Items.Remove(cboFriends.Text)
End Sub
End Class
It appears you are looking for the SelectedText property
To set it to a blank string, do the following
cboFriends.SelectedText = ""
cboFriends.SelectedText would work if the text was selected, but if i type "asdfjkl;" and then press [Remove] it does nothing.
Upon further digging cboFriends.Text = "" does the trick!