Visual Studio 2012 - Collection output for listing? - vb.net

So basically I'm trying to create a file manager, and I'm failing at it. I've attempted to find out and haven't found a single response on why I get a (Collection) when I'm loading file names from zip / rar files.
The code is as follows
Imports System.IO
Public Class Form1
Private Sub modFolderButton_Click(sender As Object, e As EventArgs) Handles modFolderButton.Click
Dim modFolder
modFolder = modFolderText.Text
If IO.Directory.Exists(modFolder) Then
MsgBox("Location Successfully Set; " + modFolder, MsgBoxStyle.Information)
Else
MsgBox("Error; Invalid Location Set")
Exit Sub
End If
End Sub
Private Sub starboundButton_Click(sender As Object, e As EventArgs) Handles starboundButton.Click
Dim starboundFolder
starboundFolder = starboundFolderText.Text
If IO.Directory.Exists(starboundfolder) Then
MsgBox("Location Successfully Set; " + starboundFolder, MsgBoxStyle.Information)
Else
MsgBox("Error; Invalid Location Set")
Exit Sub
End If
End Sub
Private Sub listRefreshButton_Click(sender As Object, e As EventArgs) Handles listrRefreshButton.Click
Dim modFolder
Dim listModsDetected
modsDetectedList.Items.Clear()
modFolder = "C:\"
listModsDetected = My.Computer.FileSystem.GetFiles(modFolder, FileIO.SearchOption.SearchTopLevelOnly, "*.zip")
modsDetectedList.Items.Add("None Detected!")
For Each fileName As String In listModsDetected
modsDetectedList.Items.Remove("None Detected!")
modsDetectedList.Items.Add(listModsDetected)
Next
End Sub
End Class

modsDetectedList.Items.Add(listModsDetected)
You just added the collection itself to your list.
That's why it shows (collection).
You probably want to add each item in the collection to your list.
That's what For Each gives you in fileName.

You're adding:
modsDetectedList.Items.Add(listModsDetected)
Eho's ToString is its typename.
Instead use modsDetectedList.Items.AddRange (if it exists) or add the filename in the loop.

Related

How to save checkbox value in xml using vb.net

I know, maybe this is a question that comes up quite often, but I haven't been able to work on it.
How can I save this checkbox values in an XML file using VB.Net ?
Private Sub ChkVul_Click(sender As Object, e As EventArgs) Handles ChkVul.Click
If ChkVul.Checked = True Then
Me.pnlInsert.Visible = True
Else
Me.pnlInsert.Visible = False
End If
End Sub
Before I provide you with an answer, I wanted to recommend a slight code change. Since you are setting the Boolean value of pnlInsert.Visible based on a condition, which itself returns a Boolean value, simply get rid of the conditional check in the first place:
pnlInsert.Visible = ChkVul.Checked
Now to your question. What you are essentially asking is how to write a value to an XML file. Something to consider is that XML is only a markup language. At the end of the day, an XML file is simply a file that contains formatted text.
If you do not already have an XML file to read from, simply create a new instance of a XDocument (documentation). If you do have an XML file, then create a new instance of a XDocument by calling the static XDocument.Load method (documentation). Here is a function that takes in a file location and attempts to load a XDocument, if it is unable to then it returns a blank XDocument with a single <root> element:
Private Function LoadOrCreateXml(filename As String) As XDocument
Dim document = New XDocument()
document.Add(New XElement("root"))
Try
If (Not String.IsNullOrWhiteSpace(filename) AndAlso IO.File.Exists(filename)) Then
document = XDocument.Load(filename)
End If
Catch ex As Exception
' for the sake of this example, just silently fail
End Try
Return document
End Function
Now that you have an XDocument, it is just a matter of writing the value. You did not provide any details as to where the value should go or what the tag name should be, so I am going to assume that it should be a child of the <root /> element and the value would look something like this: <ChkVul>true/false</ChkVul>.
To do this, we will need to get the <root /> element by calling the Element method (documentation) on the XDocument to get the element and then call the Add method (documentation) on the resulting XElement to add our node with the value:
Dim document = LoadOrCreateXml("my-xml-file.txt")
document.Element("root").Add(New XElement("ChkVul", ChkVul.Checked))
The final piece of all this is to write the in-memory XDocument back to the file. You can leverage the XDocument.Save method (documentation):
Dim filename = "my-xml-file.txt"
Dim document = LoadOrCreateXml(filename)
document.Element("root").Add(New XElement("ChkVul", ChkVul.Checked))
document.Save(filename)
Maybe this is what you have in mind. I tested this with other controls,
Public Class Form1
Private SavePath As String = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
"MyControls.xml") 'some valid path <-----------<<<
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
SaveCheckedState(ChkVul, "ChkVul", True)
End Sub
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
If IO.File.Exists(SavePath) Then
Try
MyControls = XElement.Load(SavePath)
For Each el As XElement In MyControls.Elements
Dim ctrl() As Control = Me.Controls.Find(el.#name, True)
If ctrl.Length > 0 Then
Dim chkd As System.Reflection.PropertyInfo = ctrl(0).GetType().GetProperty("Checked")
Dim chkdV As Boolean = Boolean.Parse(el.#checked)
chkd.SetValue(ctrl(0), chkdV)
End If
Next
Catch ex As Exception
'todo
End Try
End If
End Sub
Private Sub ChkVul_CheckedChanged(sender As Object, e As EventArgs) Handles ChkVul.CheckedChanged
If ChkVul.Checked Then
Me.pnlInsert.Visible = True
Else
Me.pnlInsert.Visible = False
End If
SaveCheckedState(ChkVul, "ChkVul")
End Sub
Private Sub RadioButton1_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged
SaveCheckedState(RadioButton1, "RadioButton1")
End Sub
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
SaveCheckedState(CheckBox1, "CheckBox1")
End Sub
Private MyControls As XElement = <controls>
</controls>
Private Sub SaveCheckedState(Ctrl As Control,
Name As String,
Optional Save As Boolean = False)
If Ctrl.GetType().GetProperty("Checked") IsNot Nothing Then
Dim chkd As System.Reflection.PropertyInfo = Ctrl.GetType().GetProperty("Checked")
Dim chkdV As Boolean = CBool(chkd.GetValue(Ctrl))
Dim ie As IEnumerable(Of XElement)
ie = From el In MyControls.Elements
Where el.#name = Ctrl.Name
Select el Take 1
Dim thisXML As XElement
If ie.Count = 0 Then
thisXML = <ctrl name=<%= Name %>></ctrl>
MyControls.Add(thisXML)
Else
thisXML = ie(0)
End If
thisXML.#checked = chkdV.ToString
End If
If Save Then
Try
MyControls.Save(SavePath)
Catch ex As Exception
'todo
' Stop
End Try
End If
End Sub
End Class

Could someone explain where are the errors in this code in vb.net

I'm new to this site and also a newbee in vb.net, I created a simple form in vb.net, a form with 3 buttons, by clicking Button1 Species1.txt is created, and by clicking Button2 the lines in Species1.txt are copied in a String Array called astSpecies(), and by Button3 the String Array is copied in a new file, named Species2.txt, below is the code.
Public Class Form4
Dim astSpecies() As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myStreamWriter = New StreamWriter("C:\Users\Administrator\Documents\species1.txt", True)
myStreamWriter.WriteLine("Pagasius pangasius")
myStreamWriter.WriteLine("Meretrix lyrata")
myStreamWriter.WriteLine("Psetta maxima")
myStreamWriter.WriteLine("Nephrops norvegicus")
myStreamWriter.WriteLine("Homarus americanus")
myStreamWriter.WriteLine("Procambarus clarkii")
myStreamWriter.Close()
MsgBox("list complete")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim myStreamReader = New StreamReader("C:\Users\Administrator\Documents\species1.txt")
Dim i As Integer
Dim stOutput As String
stOutput = ""
Do While Not myStreamReader.EndOfStream
astSpecies(i) = myStreamReader.ReadLine
stOutput = stOutput & astSpecies(i) & vbNewLine
i = i + 1
Loop
myStreamReader.Close()
MsgBox(stOutput)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim myStreamWriter = New StreamWriter("C:\Users\Administrator\Documents\species2.txt", True)
Dim o As Integer
Do While o <= astSpecies.Length
myStreamWriter.WriteLine(astSpecies(o))
o = o + 1
Loop
myStreamWriter.Close()
End Sub
End Class
First of all, you should make a few settings when it comes to VB.Net. 1.) set Option Strict to On 2.) remove the VB6 namespace. VB6 is the old Visual Basic. There are many functions in this that are inefficient from today's perspective. So please do not write MsgBox() but MessageBox.Show("").
(If you still need control characters such as NewLine or Tab, you can set a selective reference with Imports Microsoft.VisualBasic.ControlChars. Sounds contradictory, but it is useful, because why should you also write ChrW(9), it is not legible.)
I quickly started a project myself and wrote whatever you wanted.
I still don't quite understand why you first write things into a text file, then read them out, and then write that into a second text file – I want to say: where do the strings originally come from? The strings must have been there already? Anyway, I filled a List(of String) in the Button2_Click procedure. This has the advantage that you don't have to know in advance how many strings are coming, and you can sort them later and so on ...
You should also discard all Writers when you no longer need them. So use Using. Otherwise it can happen that the written files are not discarded and you can no longer edit the file.
Imports Microsoft.VisualBasic.ControlChars
Imports Microsoft.WindowsAPICodePack.Dialogs
Public NotInheritable Class FormMain
Private Path As String = ""
Private allLines As New List(Of String)
Private Sub FormMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.BackColor = Color.FromArgb(161, 181, 165)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using OFolderD As New CommonOpenFileDialog
OFolderD.Title = "Ordner auswählen"
OFolderD.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
OFolderD.IsFolderPicker = True
If OFolderD.ShowDialog() = CommonFileDialogResult.Ok Then
Path = OFolderD.FileName
Else
Return
End If
End Using
Path &= "\Data.txt"
Using txtfile As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(Path, True)
txtfile.WriteLine("Pagasius pangasius")
txtfile.WriteLine("Meretrix lyrata")
txtfile.WriteLine("Psetta maxima")
txtfile.WriteLine("Nephrops norvegicus")
txtfile.WriteLine("Homarus americanus")
txtfile.WriteLine("Procambarus clarkii")
txtfile.Close()
End Using
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'read all Text
Dim RAT() As String = System.IO.File.ReadAllLines(Path, System.Text.Encoding.UTF8)
If RAT.Length = 0 OrElse RAT.Length = 1 Then
MessageBox.Show("The File only contains 0 or 1 characters.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand)
Return
End If
allLines.AddRange(RAT)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim Pfad_txt As String = Path.Substring(0, Path.LastIndexOf("\"c)) & "\Data2.txt"
Using txtfile As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(Pfad_txt, True)
For Each Line As String In allLines
txtfile.WriteLine(Line)
Next
txtfile.Close()
End Using
End Sub
End Class
By the way: I use a FolderBrowserDialog in the Button1_Click procedure. This should be done so that the program also runs properly on other PCs. In order to be able to use the FBD, you have to download Microsoft.WindowsAPICodePack.Dialogs in Visual Studio's own Nuget package manager.
how to set Option Strict to On
How to uncheck VB6.
how to install FolderBrowserDialog in Visual Studio
Button1
If you want to use a StreamWriter it should be disposed. Classes in the .net Framework that have a Dispose method may use resources outside of the framework which need to be cleaned up. The classes shield you from these details by provided a Dispose method which must be called to properly do the clean up. Normally this is done with Using blocks.
I used a string builder which saves creating and throwing away a string each time you change the string. You may have heard that strings are immutable (cannot be changed). The StringBuilder class gets around this limitation. It is worth using if you have many changes to your string.
The File class is a .net class that you can use to read or write files. It is not as flexible as the stream classes but it is very easy to use.
Button 2
When you declared your Array, you declared an array with no elements. You cannot add elements to an array with no space for them. As Daniel pointed out, you can use the .net class List(Of T) The T stands for Type. This is very good suggestion when you don't know the number of elements in advance. I stuck with the array idea by assigning the array returned by File.ReadAllLines to the lines variable.
You get the same result by simply reading all the text and displaying it.
Button 3
Again I used the File class here which allows you to complete your task in a single line of code. Using 2 parameters for the String.Join method, the separator string and the array to join, we reproduce the original file.
Private SpeciesPath As String = "C:\Users\maryo\Documents\species1.txt"
Private lines As String()
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sb As New StringBuilder
sb.AppendLine("Pagasius pangasius")
sb.AppendLine("Meretrix lyrata")
sb.AppendLine("Psetta maxima")
sb.AppendLine("Nephrops norvegicus")
sb.AppendLine("Homarus americanus")
sb.AppendLine("Procambarus clarkii")
File.WriteAllText(SpeciesPath, sb.ToString)
MsgBox("list complete")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
lines = File.ReadAllLines(SpeciesPath)
MessageBox.Show(String.Join(Environment.NewLine, lines))
'OR
MessageBox.Show(File.ReadAllText(SpeciesPath))
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
File.WriteAllLines("C:\Users\maryo\Documents\species2.txt", lines))
End Sub

Importing data from text file in VB.NET

So, I am trying to develop a book database. I have created a table with 11 columns which populates a DGV, where only 6 columns are showed. The full data of each book is shown in a lower part of the form, where I have textboxes, which are bounded (BindingSource) to the table, that change as I move in the DGV.
Now, what I want to do is to have the posibility to export/import data from a file.
I have accomplished the exporting part with the following code:
Private Sub BtnExport_Click(sender As Object, e As EventArgs) Handles BtnExport.Click
Dim txt As String = String.Empty
For Each row As DataGridViewRow In DbdocsDataGridView.Rows
For Each cell As DataGridViewCell In row.Cells
'Add the Data rows.
txt += CStr(cell.Value & ","c)
Next
'Add new line.
txt += vbCr & vbLf
Next
Dim folderPath As String = "C:\CSV\"
File.WriteAllText(folderPath & "DataGridViewExport.txt", txt)
End Sub
However, I can't manage to import from the txt. What I've tried is this: https://1bestcsharp.blogspot.com/2018/04/vb.net-import-txt-file-text-to-datagridview.html
It works perfectly if you code the table and it populates de DGV without problem. I can't see how should I adapt that code to my need.
Private Sub BtnImport_Click(sender As Object, e As EventArgs) Handles BtnImport.Click
DbdocsDataGridView.DataSource = table
Dim filas() As String
Dim valores() As String
filas = File.ReadAllLines("C:\CSV\DataGridViewExport.txt")
For i As Integer = 0 To filas.Length - 1 Step +1
valores = filas(i).ToString().Split(",")
Dim row(valores.Length - 1) As String
For j As Integer = 0 To valores.Length - 1 Step +1
row(j) = valores(j).Trim()
Next j
table.Rows.Add(row)
Next i
End Sub
That is what I've tried so far, but I always have an exception arising.
Thanks in advance to anyone who can give me an insight about this.
The DataTable class has built-in methods to load/save data from/to XML called ReadXml and WriteXml. Take a look at example which uses the overload to preserve the schema:
Private ReadOnly dataGridViewExportPath As String = IO.Path.Combine("C:\", "CSV", "DataGridViewExport.txt")
Private Sub BtnExport_Click(sender As Object, e As EventArgs) Handles BtnExport.Click
table.WriteXml(path, XmlWriteMode.WriteSchema)
End Sub
Private Sub BtnImport_Click(sender As Object, e As EventArgs) Handles BtnImport.Click
table.ReadXml(path)
End Sub
While users can manually edit the XML file that is generated from WriteXML, I would certainly not suggest it.
This is code which writes to a text file:
speichern means to save.
Note that I use a # in my example for formatting reasons. When reading in again, you can find the # and then you know that and that line is coming...
And I used Private ReadOnly Deu As New System.Globalization.CultureInfo("de-DE") to format the Date into German format, but you can decide yourself if you want that. 🙂
Note that I'm using a FileDialog that I downloaded from Visual Studio's own NuGet package manager.
Private Sub Button_speichern_Click(sender As Object, e As EventArgs) Handles Button_speichern.Click
speichern()
End Sub
Private Sub speichern()
'-------------------------------------------------------------------------------------------------------------
' User can choose where to save the text file and the program will save it .
'-------------------------------------------------------------------------------------------------------------
Dim Path As String
Using SFD1 As New CommonSaveFileDialog
SFD1.Title = "store data in a text file"
SFD1.Filters.Add(New CommonFileDialogFilter("Textdatei", ".txt"))
SFD1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
If SFD1.ShowDialog() = CommonFileDialogResult.Ok Then
Path = SFD1.FileName & ".txt"
Else
Return
End If
End Using
Using textfile As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(Path, True, System.Text.Encoding.UTF8)
textfile.WriteLine("Timestamp of this file [dd.mm.yyyy hh:mm:ss]: " & Date.Now.ToString("G", Deu) & NewLine & NewLine) 'supposed to be line break + 2 blank lines :-)
textfile.WriteLine("your text")
textfile.WriteLine("#") 'Marker
textfile.Close()
End Using
End Sub
Private Sub FormMain_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
speichern()
End Sub
And this is to read from a text file:
'read all Text
Dim RAT() As String = System.IO.File.ReadAllLines(Pfad, System.Text.Encoding.UTF8)
If RAT.Length = 0 Then Return Nothing
For i As Integer = 0 To RAT.Length - 1 Step 1
If RAT(i) = "#" OrElse RAT(i) = "" Then Continue For
'do your work here with (RAT(i))
Next

How do I use VB Application.DoEvent?

I have a process that works well when it's running against small files but gives an "Message=Managed Debugging Assistant 'ContextSwitchDeadlock' : 'The CLR has been unable to transition from COM context 0xa5b8e0 to COM context 0xa5b828 for 60 seconds." error when running against large files. I'm pretty new to VB and did some investigating and found that using Application.DoEvent seemed to be recommended. I was hoping that someone could show me an example of how to use that. If I'm executing a Sub called "Process1", how would I use the DoEvent to prevent it from timing out. Ideally I'd like to add a progress bar as well but I have ot idea on that one either. I'd appreciate any help. Please keep it simple as I'm new to VB/VS.
This is the comment from my first question showing the code. Process1 calls a sub named ArchDtlCopyFile1 which scrolls through the values in a list view, copying the files named in the items to a different location. It then calls ArchDtlCheckCopy1 to scroll through the list view again to ensure that the copy was done. It then decides if the source file should be deleted and do it if required. Finally it inserts a row in an Access table documenting the change made.
Private Sub Process1()
If ReturnCode = 0 Then
ArchDtlCopyFile1()
Else
' MessageBox.Show("Error code coming in is: " & CStr(ReturnCode))
End If
If ReturnCode = 0 Then
ArchDtlCheckCopy1()
Else
' MessageBox.Show("Error code for check copy is: " & CStr(ReturnCode))
End If
End Sub
Private Sub ArchDtlCopyFile1()
intLVIndex = 0
' Copy the file from the source computer onto the NAS
Do While intLVIndex < intMaxFileIndex
Try
' Select the row from the LVFiles ListView, then move the first column (0) into strSourceFilePath and the last
' column (3) into strDestFilePath. Execute the CopyFile method to copy the file.
LVFiles.Items(intLVIndex).Selected = True
strSourceFilePath = LVFiles.SelectedItems(intLVIndex).SubItems(0).Text
strDestFilePath = LVFiles.SelectedItems(intLVIndex).SubItems(3).Text
My.Computer.FileSystem.CopyFile(strSourceFilePath, strDestFilePath, overwrite:=False)
Catch ex As Exception
' Even if there's an error with one file, we should continue trying to process the rest of the files
Continue Do
End Try
intLVIndex += 1
Loop
End Sub
Private Sub ArchDtlCheckCopy1()
intLVIndex = 0
intLVError = 0
' ' Check each file was copied onto the NAS
Do While intLVIndex < intMaxFileIndex
' Select the row from the LVFiles ListView, then move the last column (3) into strDestFilePath.
' Use the FileExists method to ensure the file was created on the NAS. If it was, call the
' ADetDelete Sub to delete the source file from the user's computer.
LVFiles.Items(intLVIndex).Selected = True
strSourceFilePath = LVFiles.SelectedItems(intLVIndex).SubItems(0).Text
strDestFilePath = LVFiles.SelectedItems(intLVIndex).SubItems(3).Text
strSourceFile = LVFiles.SelectedItems(intLVIndex).SubItems(1).Text
Try
If My.Computer.FileSystem.FileExists(strDestFilePath) Then
' Archive file was created so go ahead and delete the source file
'If strSourceFile = myCheckFile Then
' strDestFile = LVFiles.SelectedItems(intLVIndex).SubItems(3).Text
'End If
If RBArchive.Checked = True Then
ArchDtlDeleteFile(strSourceFilePath)
End If
PrepareDtlVariables()
ADtlAddRow()
Else
MessageBox.Show("File not found. " & strDestFilePath)
End If
Catch ex As Exception
ErrorCode = "ARC6"
MessageCode = "Error while checking file copy"
ReturnCode = 8
End Try
intLVIndex += 1
Loop
End Sub
Here's a simplified example:
Imports System.ComponentModel
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
BackgroundWorker1.WorkerReportsProgress = True
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Button1.Enabled = False
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
For i As Integer = 1 To 20
BackgroundWorker1.ReportProgress(i) ' you can pass anything out using the other overloaded ReportProgress()
System.Threading.Thread.Sleep(1000)
Next
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
' you can also use e.UserState to pass out ANYTHING
Label1.Text = e.ProgressPercentage
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MessageBox.Show("Done!")
Button1.Enabled = True
End Sub
End Class

Is there a way to get the input from a Load event handler (entered via inputBox) to be used Globally in the program?

I am creating a form that will prompt the user to enter a file name upon loading the file. The issue I encounter is that my variable I use to store the input is not recognized in another one of my procedures. The code here shows my current set up.
Imports System.IO
Public Class frmEmployee
Sub frmEmployee_load(ByVal sender As Object, e As System.EventArgs)
Dim strFileName = InputBox("Please name the file you would like to save the data to: ")
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
txtEmail.Clear()
txtExtension.Clear()
txtFirst.Clear()
txtLast.Clear()
txtMiddle.Clear()
txtNumber.Clear()
txtPhone.Clear()
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim inputFile As New StreamWriter(strFileName)
If File.Exists(strFileName) = True Then
inputFile = File.CreateText(strFileName)
inputFile.Write(txtEmail.Text)
inputFile.Write(txtExtension.Text)
inputFile.Write(txtFirst.Text)
inputFile.Write(txtLast.Text)
inputFile.Write(txtMiddle.Text)
inputFile.Write(txtNumber.Text)
inputFile.Write(txtPhone.Text)
inputFile.Write(cmbDepart.Text)
Else
MessageBox.Show("" & strFileName & "Cannot be created or found.")
End If
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
End Class
The load event handler is where I want the user to input the name of the file.
Change the scope of your variable to outside of your load method...
Public Class frmEmployee
Private strFileName As String
Sub frmEmployee_load(ByVal sender As Object, e As System.EventArgs)
strFileName = InputBox("Please name the file you would like to save the data to: ")
End Sub
You could use My.Settings and load the file string there and save it. All forms can now access that. When you close the the app set it to String.Empty if you want it to be.
You also could be taking advantage of a class object for the fields you are capturing then using either BinaryFormatter or XmlSerializer to store the data. Better databinding, creation and reconstruction using an object.
My.Settings.Filename = Inputbox("Filename?")
My.Settings.Save()
The problem with the approach you have there is that your variabl strFileName is scoped to the class frmEmployee.
You need to set up a genuinely global variable (at the application startup) an then use that. So you will need a Sub Main as an entry point to your application See here, and just before that create a public variable to hole the file name.
So you might have something like this for your application startup:
Public fileNametoUse as string
Public Sub Main()
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(New Form1)
End Sub
Then in you load sub for frmEmployee you would have:
fileNametoUse = InputBox("Please name the file you would like to save the data to: ")