Calling a procedure from its non native form - vb.net

Ok, so
frmResult populates a ListView with various calculations
frmMenu has an export button (see code below). Pressing this is supposed to export the data in the ListView to a txt file. Currently, this button does not work. It says, List View is undeclared - obviously because the code shown below is not 'seeing' data held in frmResult
Question – how do I call the procedures stored in frmResult so that frmMenu can 'see' it.
Public Sub btnExport_Click(sender As Object, e As EventArgs) Handles btnExport.Click
Dim fileSaved As Boolean
Dim filePath As String
Do Until fileSaved
'Request filename from user
Dim saveFile As String = InputBox("Enter a file name to save this message")
'Click Cancel to exit saving the work
If saveFile = "" Then Exit Sub
'
Dim docs As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
filePath = IO.Path.Combine(docs, "Visual Studio 2013\Projects", saveFile & ".txt")
fileSaved = True
If My.Computer.FileSystem.FileExists(filePath) Then
Dim msg As String = "File Already Exists. Do You Wish To Overwrite it?"
Dim style As MsgBoxStyle = MsgBoxStyle.YesNo Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Critical
fileSaved = (MsgBox(msg, style, "Warning") = MsgBoxResult.Yes)
End If
Loop
'the filePath String contains the path you want to save the file to.
Dim rtb As New RichTextBox
rtb.AppendText("Generation, Num Of Juveniles, Num of Adults, Num of Semiles, Total" & vbNewLine)
For Each saveitem As ListViewItem In ListView1.Items
rtb.AppendText(
saveitem.Text & ", " &
saveitem.SubItems(1).Text & ", " &
saveitem.SubItems(2).Text & ", " &
saveitem.SubItems(3).Text & ", " &
saveitem.SubItems(4).Text & vbNewLine)
Next
rtb.SaveFile(filePath, RichTextBoxStreamType.PlainText)
End Sub

Is this what you mean?
Public Sub Init()
'... (all the code)
End Sub
Private Sub Results_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call Init()
End Sub
You can call Init() from every form load you want. Maybe you want to create a module and store there your methods.
By the way, you only use Function when your methods needs to return a value.
If your code uses elements of the form (or other objects not constant) you need to pass those to the method, like this:
Public Sub Init(myListView As ListView)
myListView.Items.Add("something")
'...
End Sub
Private Sub Results_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call Init(ListView1)
End Sub
You can add as many parameters as you need. You have to learn the basics before going ant further.

This is a great piece of literature for those struggling with the basics like myself.
You can write code to access objects on a different form. However, you must fully identify the name of the object by preceding it with the object variable name.
Dim resultsForm As New frmResults
resultsForm.lblAverage.Text = sngAverage.ToString()
In these statements, for example, I have declared an object variable called resultsForm that is linked to the form frmResults. The second statement assigns the string value of sngAverage to the lblAverage label box on the frmResults form.
In my code, I needed to change the line that said:
For Each saveitem As ListViewItem In ListView1.Items
To this:
For Each saveitem As ListViewItem In Results.ListView1.Items
I also needed to make sure that the procedure on formResults was made Public not Private

Related

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 to get ListView.SubItems

I'm trying to make a program that inputs text into a document depending on the user input, and I am currently displaying it as a ListView.
I can't figure out how to get the SubItem from the item, as this is my current code.
For Each item In ListView1.Items
Dim inputString72 As String = "#bot.command()" + vbNewLine
My.Computer.FileSystem.WriteAllText(
SaveFileDialog1.FileName, inputString72, True)
Dim inputString73 As String = "async def " + item.Text + "(ctx):" + vbNewLine
My.Computer.FileSystem.WriteAllText(
SaveFileDialog1.FileName, inputString73, True)
Dim inputString74 As String = " await ctx.send('" + THE SUBITEM OF THE ITEM GOES HERE + "')" + vbNewLine
My.Computer.FileSystem.WriteAllText(
SaveFileDialog1.FileName, inputString74, True)
Next
I think it would be more efficient to use the .net File class. No need to call the method several times in each iteration. From the docs. "The WriteAllText method opens a file, writes to it, and then closes it. " That is a lot of openning and closing. Build a string with a StringBuilder (which is mutable) and then write once to the file.
I used interpolated strings (it is preceded by a $) which allows you to put a variable directly in a string surrounded by braces.
SubItem indexes start at 0 with the first column. The .Text property of the SubItem will return its contents.
Private Sub WriteListViewToFile(FilePath As String)
Dim sb As New StringBuilder
For Each item As ListViewItem In ListView1.Items
sb.AppendLine("#bot.command()")
sb.AppendLine($"async def {item.Text}(ctx):")
sb.AppendLine($" await ctx.send('{item.SubItems(1).Text}')")
Next
File.WriteAllText(FilePath, sb.ToString)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If SaveFileDialog1.ShowDialog = DialogResult.OK Then
WriteListViewToFile(SaveFileDialog1.FileName)
End If
End Sub

VB.NET how to save listview with savefiledialog

Something's wrong in my code, i want to save listview item into text file using savefiledialog.
I'm getting error "Overload resolution failed because no accessible 'WriteAllLines' accepts this number of arguments."
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles ChromeButton3.Click
Dim s As New SaveFileDialog
s.Filter = "text|*.txt"
s.Title = "Save Your Hits"
If s.ShowDialog = Windows.Forms.DialogResult.OK Then
For Each myItem As ListViewItem In ListView1.Items
File.WriteAllLines(myItem.Text & vbNewLine & myItem.SubItems(1).Text & vbNewLine & myItem.SubItems(2).Text & vbNewLine & myItem.SubItems(3).Text & vbNewLine & vbNewLine)
Next
End If
End Sub
Your error
Overload resolution failed
can be corrected by looking at the documentation. It is a good idea to do this with any unfamiliar method. Just google the method followed by "in .net" The first link that came up is https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealllines?view=netframework-4.8
And the first topic in the documentation is overloads. I think you can see that none of the overloads match what you tried to pass.
As was mentioned in comments File.Write All lines isn't really appropriate for your purposes. Instead of making all those lines and a double line between records, Make each row a single line separating each field by a comma. I used a StringBuilder which provides a mutable (changeable) datatype (unlike a String which is immutable). Saves the compiler from throwing away and creating new strings on every iteration.
I appended a new line on each iteration containing an interpolated string. An interpolated string starts with the $. This allows you to directly mix in variables enclosed in { } with the literal characters.
After the loop, you convert the StringBuilder to a String and write to the file with the file name provided by the dialog box.
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim s As New SaveFileDialog
s.Filter = "text|*.txt"
s.Title = "Save Your Hits"
If s.ShowDialog = DialogResult.OK Then
Dim fileName = s.FileName
Dim sb As New StringBuilder
For Each myItem As ListViewItem In ListView1.Items
sb.AppendLine($"{myItem.Text},{myItem.SubItems(1).Text},{myItem.SubItems(2).Text},{myItem.SubItems(3).Text}")
Next
File.WriteAllText(fileName, sb.ToString)
End If
End Sub

VB.NET Program is always reading last created textfile

Trying to create a login form,
My coding is currently:
Imports System
Imports System.IO
Public Class frmLogin
Dim username As String
Dim password As String
Dim fileReader As String
Dim folderpath As String
Dim files As Integer
Dim filepath As String
Public Structure info
Dim U As String
Dim P As String
End Structure
Dim details As info
Private Sub btnlogin_Click(sender As Object, e As EventArgs) Handles btnlogin.Click
If txtusername.Text = details.U And txtpassword.Text = details.P Then
MessageBox.Show("Correct!")
frmmenu.Show()
Me.Hide()
Else
MessageBox.Show("wrong")
txtusername.Clear()
txtpassword.Clear()
End If
End Sub
Private Sub btncreate_Click(sender As Object, e As EventArgs) Handles btncreate.Click
frmcreate.Show()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
files = files + 1
filepath = "C:\Users\TheGlove\Desktop\Alex's Program\loginfile" & files & ".txt"
Dim di As DirectoryInfo = New DirectoryInfo("C:\Users\TheGlove\Desktop\Alex's Program")
folderpath = "C:\Users\TheGlove\Desktop\Alex's Program"
files = System.IO.Directory.GetFiles(folderpath, "*.txt").Count
For Each fi In di.GetFiles()
MsgBox(fi.Name)
Dim FILE = System.IO.File.ReadAllLines("C:\Users\TheGlove\Desktop\Alex's Program\loginfile" & files & ".txt")
Dim myArray As String() = FILE
details.U = myArray(0)
details.P = myArray(1)
Next
End Sub
End Class
Button 1 will be merged with btnlogin when i get it working and for now is currently just a seperate button to read each textfile.
When each button is pressed (Button 1 -> btnlogin), only the last created textfile is correct.
By the looks of things, your code does read all the text files, but keeps overwriting details.u and details.p with the value retrieved from each file. So, when the loop gets to the last file, those values are what ends up in the details object.
I'm assuming that you want to read all the usernames and passwords into a list and check the details in the TextBoxes against that list, so .. Your code should probably be something like the code below (see the code comments for an explanation of some of the differences.
Before we get to the code, can give you a couple of pointers.
Firstly, always try to use names that are meaningful. Defining your structure as Info is not as meaningful as it could be. For example, you would be better calling it UserInfo and rather than use P and U, you would be better using Password and UserName. It may not matter so much right now, but when you start writing larger more complex programs, and have to come back to them in 6 months time to update them, info.P or details.P aren't as informative as the suggested names.
Secondly, as #ajd mentioned. Don't use magic strings. Create one definition at the beginning of your code which can be used throughout. Again it makes maintenance much easier if you only have to change a string once instead of multiple times, and reduces the chance of mistakes.
Finally, several of the variables you have defined aren't used in your code at all. Again, at this level, it isn't a major issue, but with large programs, you could end up with a bigger memory footprint than you want.
Dim username As String
Dim password As String
Dim fileReader As String
Dim folderpath As String = "C:\Users\TheGlove\Desktop\Alex's Program"
Dim files As Integer
Dim filepath As String
Public Structure UserInfo
Dim Name As String
Dim Password As String
End Structure
'Change details to a list of info instead of a single instance
Dim userList As New List(Of UserInfo)
Private Sub Btnlogin_Click(sender As Object, e As EventArgs) Handles btnlogin.Click
'Iterate through the list of details, checking each instance against the textboxes
For Each tempUserInfo As UserInfo In userList
If txtusername.Text = tempUserInfo.Name And txtpassword.Text = tempUserInfo.Password Then
MessageBox.Show("Correct!")
frmmenu.Show()
Me.Hide()
'This is here, because after your form has opened an closed, the loop
'that checks usernames and passwords will continue. The line below exits the loop safely
Exit For
Else
MessageBox.Show("wrong")
txtusername.Clear()
txtpassword.Clear()
End If
Next
End Sub
Private Sub Btncreate_Click(sender As Object, e As EventArgs) Handles btncreate.Click
frmcreate.Show()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'clear the list of user details otherwise, if the files are loaded a second time,
'you'll get the same details added again
userList.Clear()
'This line replaces several lines in your code that searches the folder for files
'marching the search pattern
Dim fileList() As FileInfo = New DirectoryInfo(folderpath).GetFiles("loginfile*.txt")
For Each fi As FileInfo In fileList
MsgBox(fi.Name)
Dim userDetails() As String = System.IO.File.ReadAllLines(fi.FullName)
Dim tempInfo As New UserInfo With {.Name = userDetails(0), .Password = userDetails(1)}
'An expanded version of the above line is
'Dim tempInfo As New info
'tempInfo.U = userDetails(0)
'tempInfo.P = userDetails(1)
userList.Add(tempInfo)
Next
files = fileList.Count
End Sub

Using a textbox value for a file name

How do you use a textbox value for VB to save some text to? This is what I have so far:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles butUpdate.Click
Dim ECOLID As String
ECOLID = txtID.Text
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("?", True)
file.WriteLine("ECOL Number:")
file.WriteLine(txtID.Text)
file.Close()
End Sub
The txtID text will determine the title however how can I get it to save it as "C:/Order/'txtID'.txt" for example?
A textbox has a property called Name and this is (usually) the same as the variable name that represent the TextBox in your code.
So, if you want to create a file with the same name of your textbox you could write
file = My.Computer.FileSystem.OpenTextFileWriter(txtID.Name & ".txt", True)
However there is a big improvement to make to your code
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles butUpdate.Click
Dim ECOLID As String
ECOLID = txtID.Text
Dim fileName = txtID.Name & ".txt"
Using file = My.Computer.FileSystem.OpenTextFileWriter(fileName, True)
file.WriteLine("ECOL Number:")
file.WriteLine(txtID.Text)
End Using
End Sub
In this version the opening of the StreamWriter object is enclosed in a Using Statement. This is fundamental to correctly release the resources to the operating system when you have done to work with your file because the End Using ensures that your file is closed and disposed correctly also in case of exceptions