How to convert String into code in VB.net? - vb.net

First, let's have a look at my code:
Private Sub FormLoad(sender As Object, e As EventArgs) Handles MyBase.Load
txtMDF.Text = My.Settings.MDF
End Sub
Assume My.Settings.MDF has a string value of Application.StartupPath + "\MyDB.mdf". I get this result:
But I want the result to be:
I have tried the following links and methods:
How to convert string to code in vb.net and to view static or public variables of main project
CodeDom - But didn't understand it.

As ProGamer Suggested,
First
save you My.Settings.MDF String = None
Second
Edit your code as follows:
Private Sub FormLoad(sender As Object, e As EventArgs) Handles MyBase.Load
If My.Settings.MDF = "None" Then
txtMDF.Text = Application.StartupPath + "\MyDB.mdf"
Else
txtMDF.Text = My.Settings.MDF
End If
txtMDF.Text = My.Settings.MDF
End Sub
Third
Add the following code to YourFormClose_Event
Private Sub FormClosing(sender As Object, e As CancelEventArgs) Handles Me.Closing
My.Settings.MDF = txtMDF.Text
My.Settings.Save()
End Sub
And NOTE that you should select "User" from 'Scope Drop Down' in the Settings for MDF instead of "Application" or else My.Settings.Save() will not work and it will remain "None"
Example:

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

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

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

get file name without files extension using drag and drop vb.net

I want to drag and drop a file on a button and store the files Name without extension to a text box. Help to get out of this problem. I am getting some errors on those codes.
Private Sub Button5_DragDrop(sender As Object, e As DragEventArgs)
_Handles Button5.DragDrop
Dim files() As String = e.Data.GetData(DataFormats.FileDrop)
Dim file_name As String = Path.GetFileName(files(0))
For Each path In files
TextBox1.Text = (path)
Next
TextBox2.Text = files(0)
End Sub
Private Sub Button5_DragEnter(sender As Object, e As DragEventArgs)
_Handles Button5.DragEnter
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
e.Effect = DragDropEffects.Copy
End If
End Sub
I feel you missed setting AllowDrop feature to true
and also there is a function to get filename without extension "GetFileNameWithoutExtension"
Check the code Below
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Button5.AllowDrop = True
End Sub
Private Sub Button5_DragDrop(sender As System.Object, e As System.Windows.Forms.DragEventArgs) Handles Button5.DragDrop
Dim files() As String = e.Data.GetData(DataFormats.FileDrop)
For Each indpath In files
TextBox1.Text = Path.GetFileNameWithoutExtension(indpath) & vbNewLine & TextBox1.Text
Next
End Sub
Private Sub Button5_DragEnter(sender As System.Object, e As System.Windows.Forms.DragEventArgs) Handles Button5.DragEnter
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
e.Effect = DragDropEffects.Copy
End If
End Sub
End Class

Visual Basic Beginner ..SubStrings

I'm new to programming and I'm trying to figure out this simple question! The language is Visual Basic! The Question is below:
"Users of a computer program often like to enter numbers with commas inserted in the middle, such as "1,234,000,688". Most computer languages consider this format to be non numeric. Write a program that inputs a number containing no more than three commas, and produces a string containing the same number without the commas"
When I enter this number: 1,234,000,688 and hit Display in Visual Basic I get this error message --> Argument is out of range Exception was unhanded
I'm not exactly sure why this is happening because I'm within my strUserInput length.
My Code:
Public Class Form1
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
'Variable declarations
Dim strUserInput = txtUserInput.Text
Dim strOutputNumber1 As String
Dim strOutputNumber2 As String
Dim strOutputNumber3 As String
Dim strOutputNumber4 As String
' 1,234,000,688
strOutputNumber1 = strUserInput.Substring(0, 1)
strOutputNumber2 = strUserInput.Substring(2, 4)
strOutputNumber3 = strUserInput.Substring(5, 8)
strOutputNumber4 = strUserInput.Substring(9, 12)
lblDisplayNumber.Text = strOutputNumber1 & strOutputNumber2 & strOutputNumber3 & strOutputNumber4
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
lblDisplayNumber.Text = String.Empty
txtUserInput.Text = String.Empty
End Sub
End Class
You're getting that exception because of the way you're using substring, the last one there starts at index 9 and extends 12 characters...that would be a 22 character number, and the text you have as input is probably much shorter. You don't need to make things overly complicated for yourself using substrings, all of the above code could be greatly condensed and cleaned up by simply using String.Replace like this:
Public Class Form1
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
lblDisplayNumber.Text = txtUserInput.Text.Replace(",", "")
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
lblDisplayNumber.Text = String.Empty
txtUserInput.Text = String.Empty
End Sub
End Class

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!