Problems Reading File - vb.net

Currently having issues reading data from a file, and assigning it to the text-boxes on my form. The code runs without throwing an error, but no data/values are passed to the text-boxes and they remain blank. Below is my code:
Imports System.IO
Public Class ReadingEmployeeData
' Declare filename
Dim FileName As String
Private Sub NextButton_Click(sender As Object, e As EventArgs) Handles NextButton.Click
' Constant for holding the number of fields
Const NumFields As Integer = 8
' Declare variables
Dim FileStream As StreamReader
Dim Count As Integer
Try
' Open file
FileStream = File.OpenText(FileName)
' Read the data
For Count = 1 To NumFields
FirstText.Text = FileStream.ReadLine()
MiddleText.Text = FileStream.ReadLine()
LastText.Text = FileStream.ReadLine()
NumberText.Text = FileStream.ReadLine()
DepartmentText.Text = FileStream.ReadLine()
PhoneText.Text = FileStream.ReadLine()
ExtText.Text = FileStream.ReadLine()
EmailText.Text = FileStream.ReadLine()
Next Count
Catch ex As Exception
MessageBox.Show("That file can not be opened.")
Finally
FileStream.Close()
End Try
End Sub
Private Sub ReadingEmployeeData_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Get the filename from user
FileName = InputBox("Please enter the name of the file")
End Sub
Private Sub ExitButton_Click(sender As Object, e As EventArgs) Handles ExitButton.Click
Me.Close()
End Sub
End Class

Try using Io.StreamReader, And there is no need to NumFields:
Imports System.IO
Public Class ReadingEmployeeData
' Declare filename
Dim FileName As String
Private Sub NextButton_Click(sender As Object, e As EventArgs) Handles NextButton.Click
' Declare variables
Dim FileStream As StreamReader
Dim Count As Integer
Try
' Open file
Using sr As New Io.StreamReader(FileName)
' Read the data
FirstText.Text = sr.ReadLine()
MiddleText.Text = sr.ReadLine()
LastText.Text = sr.ReadLine()
NumberText.Text = sr.ReadLine()
DepartmentText.Text = sr.ReadLine()
PhoneText.Text = sr.ReadLine()
ExtText.Text = sr.ReadLine()
EmailText.Text = sr.ReadLine()
sr.Close()
End Using
Catch ex As Exception
MessageBox.Show("That file can not be opened.")
End Try
End Sub
Private Sub ReadingEmployeeData_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Get the filename from user
FileName = InputBox("Please enter the name of the file")
End Sub
Private Sub ExitButton_Click(sender As Object, e As EventArgs) Handles ExitButton.Click
Me.Close()
End Sub
End Class

Related

Increasing memory usage while scrolling on listview items in vb.net

In a WinForm i have two listview(lvwTemplateCategory) one is listing folders at given directory and if you select folder, other listview(lvwTemplates) shows the files under this directory. I have also one picturebox(picTemplateImage) to show preview screenshot of that file.
While i'm scrolling on that form for 2-3 folders and 9-10 files it's memory usage goes from 62 MB to 120 MB.
I don't know how to manage the memory source also i tried to implement IDisposable but not know where to implement.
P.S. I'm using VS 2017 and calling that WinForm with .Show() method.
Also if you see non-logic codes please let me know.
Option Explicit On
Option Strict On
Imports System.IO
Public Class frmCreateNewModel
Implements IDisposable
Private Sub LoadForm(sender As Object, e As EventArgs) Handles MyBase.Load
Call AddRootDatabase()
splCreateNewModel.Panel2Collapsed = True
Size = New Size(946, 800)
End Sub
Private Sub ViewLargeIcons(sender As Object, e As EventArgs) Handles cmdViewLargeIcons.Click
lvwTemplateCategory.View = View.LargeIcon
End Sub
Private Sub ViewListIcons(sender As Object, e As EventArgs) Handles cmdViewList.Click
lvwTemplateCategory.View = View.List
End Sub
Private Sub AddRootDatabase()
Try
Dim DirDB As String = My.Settings.str_db__path_tpl
Dim DirInfoDB As New DirectoryInfo(DirDB)
For Each TplDirDB As DirectoryInfo In DirInfoDB.GetDirectories
If Not (TplDirDB.Attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
cboTemplateDatabase.Items.Add(TplDirDB.Name)
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub SelectRootDatabase(sender As Object, e As EventArgs) Handles cboTemplateDatabase.SelectedIndexChanged
Try
lvwTemplateCategory.Items.Clear()
lvwTemplates.Items.Clear()
Dim DirTempRootDir As String = My.Settings.str_db__path_tpl & "\" & cboTemplateDatabase.SelectedItem.ToString
Dim DirTempDbInfo As New DirectoryInfo(DirTempRootDir)
Dim lstIcon As Integer
For Each TplCatDir As DirectoryInfo In DirTempDbInfo.GetDirectories
If Not (TplCatDir.Attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
If imgIcons.Images.ContainsKey(TplCatDir.Name) = True Then
lstIcon = imgIcons.Images.IndexOfKey(TplCatDir.Name)
Else
lstIcon = imgIcons.Images.IndexOfKey("default")
End If
lvwTemplateCategory.Items.Add(TplCatDir.Name, lstIcon)
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub SelectTemplateCategory(sender As Object, e As EventArgs) Handles lvwTemplateCategory.SelectedIndexChanged
If (CInt(lvwTemplateCategory.SelectedItems.Count.ToString) = 0) Then
Return
End If
Dim DirTempCatDir As String = My.Settings.str_db__path_tpl & "\" & cboTemplateDatabase.SelectedItem.ToString & "\" & lvwTemplateCategory.SelectedItems(0).Text.ToString
Dim DirTempInfo As New DirectoryInfo(DirTempCatDir)
lvwTemplates.Items.Clear()
Try
For Each TplFile As FileInfo In DirTempInfo.GetFiles
If Not (TplFile.Attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
If Path.GetExtension(TplFile.Name) = ".spck" Or Path.GetExtension(TplFile.Name) = ".buspck" Then
lvwTemplates.Items.Add(TplFile.Name)
End If
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub SelectTemplate(sender As Object, e As EventArgs) Handles lvwTemplates.SelectedIndexChanged
If (CInt(lvwTemplates.SelectedItems.Count.ToString) = 0) Then
cmdQuickConfigure.Enabled = False
Return
End If
cmdQuickConfigure.Enabled = True
Dim TemplFileName As String = Path.GetFileNameWithoutExtension(lvwTemplates.SelectedItems(0).Text.ToString)
Dim DirTempDir As String = My.Settings.str_db__path_tpl & "\" & cboTemplateDatabase.SelectedItem.ToString & "\" & lvwTemplateCategory.SelectedItems(0).Text.ToString & "\" & TemplFileName
Dim imagePath As String = DirTempDir & ".png"
If File.Exists(imagePath) Then
picTemplateImage.ImageLocation = (imagePath)
picTemplateImage.SizeMode = PictureBoxSizeMode.StretchImage
picTemplateImage.Load()
Else
picTemplateImage.Image = picTemplateImage.ErrorImage
End If
txtModelName.Text = lvwTemplates.SelectedItems(0).Text.ToString
End Sub
Private Sub VisualViewControl(sender As Object, e As EventArgs) Handles cmdVisualControl.Click
If splCreateNewModel.Panel2Collapsed = False Then
splCreateNewModel.Panel2Collapsed = True
Size = New Size(946, 800)
cmdVisualControl.Text = ">>"
Else
cmdVisualControl.Text = "<<"
splCreateNewModel.Panel2Collapsed = False
Size = New Size(1300, 800)
End If
End Sub
Private Sub BrowseDirectory(sender As Object, e As EventArgs) Handles cmdBrowseDirectory.Click
Try
Dim sfd As New SelectFolderDialog With {
.Title = "Select a folder"
}
If sfd.ShowDialog(Me) = DialogResult.OK Then
txtModelDirectory.Text = sfd.FolderName
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub DialogOK(sender As Object, e As EventArgs) Handles cmdOk.Click
CreateModel()
Close()
End Sub
Private Sub DialogCancel(sender As Object, e As EventArgs) Handles cmdCancel.Click
Close()
End Sub
End Class

How to save all items listed on listbox with my.settings

I Try to save all the items from a list box with MY.SETTINGS
And Retrieved again on load
But it seems i made an error but i cannot figure out what.
its give 2 error
This is the errors
Error 3 'itemmd5' is not a member of 'MediaAdsAntivirus.My.MySettings'.
Error 2 'myitems' is not a member of 'MediaAdsAntivirus.My.MySettings'.
For this errors i just figure out i forgot to add it on settings
but now i just have a new error
This Is My New Error
Error 2 Value of type 'System.Windows.Forms.ListBox.ObjectCollection' cannot be converted to 'String'.
And i need to load them on loadfrom
How Can I List All Items Again In To It
This Is My Code:
Imports System.IO
Imports System.Security
Imports System.Security.Cryptography
Imports System.Text
Imports System.Net
Public Class form15
Dim md5hashindexer = 1
Dim md5namesave = "Hashes"
#Region "Atalhos para o principal hash_generator função"
Function md5_hash(ByVal file_name As String)
Return hash_generator("md5", file_name)
End Function
Function sha_1(ByVal file_name As String)
Return hash_generator("sha1", file_name)
End Function
Function sha_256(ByVal file_name As String)
Return hash_generator("sha256", file_name)
End Function
#End Region
Function hash_generator(ByVal hash_type As String, ByVal file_name As String)
Dim hash
If hash_type.ToLower = "md5" Then
hash = MD5.Create
ElseIf hash_type.ToLower = "sha1" Then
hash = SHA1.Create()
ElseIf hash_type.ToLower = "sha256" Then
hash = SHA256.Create()
Else
MsgBox("Type de hash inconnu : " & hash_type, MsgBoxStyle.Critical)
Return False
End If
Dim hashValue() As Byte
Dim fileStream As FileStream = File.OpenRead(file_name)
fileStream.Position = 0
hashValue = hash.ComputeHash(fileStream)
Dim hash_hex = PrintByteArray(hashValue)
fileStream.Close()
Return hash_hex
End Function
Public Function PrintByteArray(ByVal array() As Byte)
Dim hex_value As String = ""
Dim i As Integer
For i = 0 To array.Length - 1
hex_value += array(i).ToString("X2")
Next i
Return hex_value.ToLower
End Function
Private Sub BT_Parcourir_Click(sender As System.Object, e As System.EventArgs) Handles BT_Parcourir.Click
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim path As String = OpenFileDialog1.FileName
TB_path.Text = path
LB_md5.Text = md5_hash(path)
LB_sha1.Text = sha_1(path)
LB_sha256.Text = sha_256(path)
ListBox1.Items.Add(LB_md5.Text)
ListBox1.SelectedIndex += 1
Dim itemmd5 = LB_sha256.Text
Dim itemname = md5namesave + md5hashindexer
For Each line As String In ListBox1.Items
itemmd5 = My.Settings.myitems
My.Settings.itemmd5 = ListBox1.Items
Next
End If
End Sub
Private Sub LB_sha256_Click(sender As Object, e As EventArgs) Handles LB_sha256.Click
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs)
End Sub
Private Sub form15_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class
I finally decide to save in txt file and load The data again from it
This Is The Working Code
Imports System.IO
Imports System.Security
Imports System.Security.Cryptography
Imports System.Text
Imports System.Net
Public Class form15
Dim md5hashindexer = 1
#Region "Atalhos para o principal hash_generator função"
Function md5_hash(ByVal file_name As String)
Return hash_generator("md5", file_name)
End Function
Function sha_1(ByVal file_name As String)
Return hash_generator("sha1", file_name)
End Function
Function sha_256(ByVal file_name As String)
Return hash_generator("sha256", file_name)
End Function
#End Region
Function hash_generator(ByVal hash_type As String, ByVal file_name As String)
Dim hash
If hash_type.ToLower = "md5" Then
hash = MD5.Create
ElseIf hash_type.ToLower = "sha1" Then
hash = SHA1.Create()
ElseIf hash_type.ToLower = "sha256" Then
hash = SHA256.Create()
Else
MsgBox("Type de hash inconnu : " & hash_type, MsgBoxStyle.Critical)
Return False
End If
Dim hashValue() As Byte
Dim fileStream As FileStream = File.OpenRead(file_name)
fileStream.Position = 0
hashValue = hash.ComputeHash(fileStream)
Dim hash_hex = PrintByteArray(hashValue)
fileStream.Close()
Return hash_hex
End Function
Public Function PrintByteArray(ByVal array() As Byte)
Dim hex_value As String = ""
Dim i As Integer
For i = 0 To array.Length - 1
hex_value += array(i).ToString("X2")
Next i
Return hex_value.ToLower
End Function
Private Sub BT_Parcourir_Click(sender As System.Object, e As System.EventArgs) Handles BT_Parcourir.Click
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim path As String = OpenFileDialog1.FileName
TB_path.Text = path
LB_md5.Text = md5_hash(path)
LB_sha1.Text = sha_1(path)
LB_sha256.Text = sha_256(path)
ListBox1.Items.Add(LB_md5.Text)
ListBox1.SelectedIndex += 1
Dim itemmd5 = LB_sha256.Text
'For Each line As String In ListBox1.Items
'My.Settings.itemsmd5 = itemmd5
'md5hashindexer += 1
'Next
End If
Dim sb As New System.Text.StringBuilder()
For Each o As Object In ListBox1.Items
sb.AppendLine(o)
Next
System.IO.File.WriteAllText("c:\checkedfilesmd5.txt", sb.ToString())
End Sub
Private Sub LB_sha256_Click(sender As Object, e As EventArgs) Handles LB_sha256.Click
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs)
End Sub
Private Sub form15_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim lines() As String = IO.File.ReadAllLines("c:\checkedfilesmd5.txt")
ListBox1.Items.AddRange(lines)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sb As New System.Text.StringBuilder()
For Each o As Object In ListBox1.Items
sb.AppendLine(o)
Next
System.IO.File.WriteAllText("c:\checkedfilesmd5.txt", sb.ToString())
MsgBox("Dados Guardados")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim lines() As String = IO.File.ReadAllLines("c:\checkedfilesmd5.txt")
ListBox1.Items.AddRange(lines)
End Sub
Private Sub Label6_Click(sender As Object, e As EventArgs) Handles Label6.Click
ListBox1.Items.Clear()
End Sub
Private Sub Label7_Click(sender As Object, e As EventArgs) Handles Label7.Click
MsgBox("Atençao Voce Vai Apagar Todos Os Dados Ja Escaneados")
ListBox1.Items.Clear()
System.IO.File.Delete("c:\checkedfilesmd5.txt")
End Sub
End Class

Creating a Variable with StreamReader Split Results

I've recently been exposed to vb.net scripting and I am having some trouble figuring out how to accomplish a task. I'm supposed to create a program that will automate an end user process but right now it only works for one specific id(because I've hardcoded a value to make the script run). I've scripted the use of StreamReader to loop through all the possible entries, but I can't figure out how to put that result into a variable so the program will automatically read the id selected and proceed through the steps, then loop until all id's identified via StreamReader have been processed. I apologize if this has been asked before, I am not very familiar with the terminology.
Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
Application.DoEvents()
End
End Sub
Private Sub Form1_FormLoad(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
uxNote.Text = "Starting"
Me.Update()
RunApp()
Me.Close()
End Sub
Sub RunApp()
Dim b As New BostonWorkStation
Dim myHandle As Long
b.Shell_("C:\Software\Application.exe")
b.Activate("AppCaption", True)
b.Connect("AppCaption", enumStreamType1.stWindows)
uxNote.Text = myHandle.ToString
Me.Update()
b.Wait(2)
b.Pause("#378,423")
b.Tab_("user")
b.Enter("password")
b.Wait(2)
b.Shell_("C:\Software\Application2.exe")
b.Activate("App2Caption", True)
b.Wait(4)
b.Connect("App2Caption", enumStreamType1.stWindows)
uxNote.Text = myHandle.ToString
Me.Update()
b.Wait(4)
b.Smart.Create("App2Caption#726,1088", -1024, -633, 0)
b.Smart.Click(False, False)
b.Wait(3)
b.Activate("Patient Lookup", True)
b.Connect("Patient Lookup", enumStreamType1.stWindows)
uxNote.Text = myHandle.ToString
Me.Update()
b.Wait(1)
b.Pause("#104,423")
ProcessPatients(b)
b.Enter("10001") 'hardcoded id this is where I would like a variable to pull in the value
b.Wait(2)
'some more code steps here specific to what should be done once patient id has been selected
End Sub
Sub ProcessPatients(ByVal w As BostonWorkStation)
Dim record() As String
Dim sr As New StreamReader("my path for csv or txt file")
Do While sr.Peek > -1
record = sr.ReadLine.Split(CChar("|"))
Loop
sr.Close()
End Sub
I imagine it would look something like this:
Imports System.IO
Public Class Form1
Private Sub Form1_FormLoad(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
uxNote.Text = "Starting"
End Sub
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
RunApp()
End Sub
Sub RunApp()
Dim b As New BostonWorkStation
Dim myHandle As Long
b.Shell_("C:\Software\Application.exe")
b.Activate("AppCaption", True)
b.Connect("AppCaption", enumStreamType1.stWindows)
uxNote.Text = myHandle.ToString
Me.Refresh()
Application.DoEvents()
b.Wait(2)
b.Pause("#378,423")
b.Tab_("user")
b.Enter("password")
b.Wait(2)
b.Shell_("C:\Software\Application2.exe")
b.Activate("App2Caption", True)
b.Wait(4)
b.Connect("App2Caption", enumStreamType1.stWindows)
uxNote.Text = myHandle.ToString
Me.Refresh()
Application.DoEvents()
b.Wait(4)
b.Smart.Create("App2Caption#726,1088", -1024, -633, 0)
b.Smart.Click(False, False)
b.Wait(3)
b.Activate("Patient Lookup", True)
b.Connect("Patient Lookup", enumStreamType1.stWindows)
uxNote.Text = myHandle.ToString
Me.Refresh()
Application.DoEvents()
b.Wait(1)
b.Pause("#104,423")
ProcessPatients(b)
Me.Close()
End Sub
Sub ProcessPatients(ByVal w As BostonWorkStation)
Dim ID As String
Dim record() As String
Dim sr As New StreamReader("my path for csv or txt file")
Do While Not sr.EndOfStream
record = sr.ReadLine.Split(CChar("|"))
ID = record(0) ' <-- grab your "ID" from somewhere in "record"
w.Enter(ID)
w.Wait(2)
'some more code steps here specific to what should be done once patient id has been selected
Loop
sr.Close()
End Sub
End Class

Save clicks to file

I got asked a couple of days ago how to save number of clicks you have done to each button in a program to a small file, to keep track of what is most used. Since it was ages ago i dabbled with visual basic i said i would raise the question here, so here goes.
There are 5 buttons labels Button1-Button5. When a button is clicked it should look for the correct value in a file.txt and add +1 to the value. The file is structured like this.
Button1 = 0
Button2 = 0
Button3 = 0
Button4 = 0
Button5 = 0
So when button1 is clicked it should open file.txt, look for the line containing Button1 and add +1 to the value and close the file.
I have tried looking for some kind of tutorial on this but have not found it so i'm asking the collective of brains here on Stackoverflow for some guidance.
Thanks in advance.
delete file first
new ver ..
Imports System.IO.File
Imports System.IO.Path
Imports System.IO
Imports System.Text
Public Class Form1
Dim line() As String
Dim strbild As StringBuilder
Dim arr() As String
Dim i As Integer
Dim pathAndFile As String
Dim addLine As System.IO.StreamWriter
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim fileName As String = "myfile.txt"
Dim appPath As String = My.Application.Info.DirectoryPath
pathAndFile = Path.Combine(appPath, fileName)
If System.IO.File.Exists(pathAndFile) Then
'line = File.ReadAllLines(pathAndFile)
Else
Dim addLineToFile = System.IO.File.CreateText(pathAndFile) 'Create an empty txt file
Dim countButtons As Integer = 5 'add lines with your desired number of buttons
For i = 1 To countButtons
addLineToFile.Write("Button" & i & " = 0" & vbNewLine)
Next
addLineToFile.Dispose() ' and close file
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
writeToFile(1)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
writeToFile(2)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
writeToFile(3)
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
writeToFile(4)
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
writeToFile(5)
End Sub
Public Sub writeToFile(buttonId As Integer)
Dim tmpButton As String = "Button" & buttonId
strbild = New StringBuilder
line = File.ReadAllLines(pathAndFile)
Dim f As Integer = 0
For Each lineToedit As String In line
If InStr(1, lineToedit, tmpButton) > 0 Then
Dim lineSplited = lineToedit.Split
Dim cnt As Integer = lineSplited.Count
Dim newVal = addCount(CInt(lineSplited.Last()))
lineSplited(cnt - 1) = newVal
lineToedit = String.Join(" ", lineSplited)
line(f) = lineToedit
End If
f = f + 1
Next
strbild = New StringBuilder
'putting together all the reversed word
For j = 0 To line.GetUpperBound(0)
strbild.Append(line(j))
strbild.Append(vbNewLine)
Next
' writing to original file
File.WriteAllText(pathAndFile, strbild.ToString())
Me.Refresh()
End Sub
' Reverse Function
Public Function ReverseString(ByRef strToReverse As String) As String
Dim result As String = ""
For i As Integer = 0 To strToReverse.Length - 1
result += strToReverse(strToReverse.Length - 1 - i)
Next
Return result
End Function
Public Function addCount(ByVal arr As Integer) As Integer
Return arr + 1
End Function
End Class
Output in myfile.txt
Button1 = 9
Button2 = 2
Button3 = 4
Button4 = 0
Button5 = 20
Create a vb winform Application
Drag on your form 5 buttons (Button1, Button2, ... etc)
copy that :
Imports System.IO.File
Imports System.IO.Path
Imports System.IO
Imports System.Text
Public Class Form1
Dim line() As String
Dim strbild As StringBuilder
Dim arr() As String
Dim i As Integer
Dim pathAndFile As String
Dim addLine As System.IO.StreamWriter
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim fileName As String = "myfile.txt"
Dim appPath As String = My.Application.Info.DirectoryPath
pathAndFile = Path.Combine(appPath, fileName)
If System.IO.File.Exists(pathAndFile) Then
line = File.ReadAllLines(pathAndFile)
Else
Dim addLineToFile = System.IO.File.CreateText(pathAndFile) 'Create an empty txt file
Dim countButtons As Integer = 5 'add lines with your desired number of buttons
For i = 1 To countButtons
addLineToFile.Write("Button" & i & " = 0" & vbNewLine)
Next
addLineToFile.Dispose() ' and close file
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
writeToFile(1)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
writeToFile(2)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
writeToFile(3)
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
writeToFile(4)
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
writeToFile(5)
End Sub
Public Sub writeToFile(buttonId As Integer)
Dim tmpButton As String = "Button" & buttonId
strbild = New StringBuilder
line = File.ReadAllLines(pathAndFile)
i = 0
For Each lineToedit As String In line
If lineToedit.Contains(tmpButton) Then
Dim lineSplited = lineToedit.Split
Dim newVal = addCount(CInt(lineSplited.Last()))
'lineToedit.Replace(lineSplited.Last, newVal)
lineToedit = lineToedit.Replace(lineToedit.Last, newVal)
line(i) = lineToedit
End If
i = i + 1
Next
strbild = New StringBuilder
'putting together all the reversed word
For j = 0 To line.GetUpperBound(0)
strbild.Append(line(j))
strbild.Append(vbNewLine)
Next
' writing to original file
File.WriteAllText(pathAndFile, strbild.ToString())
End Sub
' Reverse Function
Public Function ReverseString(ByRef strToReverse As String) As String
Dim result As String = ""
For i As Integer = 0 To strToReverse.Length - 1
result += strToReverse(strToReverse.Length - 1 - i)
Next
Return result
End Function
Public Function addCount(ByVal arr As Integer) As Integer
Return arr + 1
End Function
End Class
Have fun ! :)CristiC777
try this on vs2013
change If confition
line = File.ReadAllLines(pathAndFile)
i = 0
For Each lineToedit As String In line
If InStr(1, lineToedit, tmpButton) > 0 Then
'If lineToedit.Contains(tmpButton) = True Then
Dim lineSplited = lineToedit.Split
Dim newVal = addCount(CInt(lineSplited.Last()))
lineToedit = lineToedit.Replace(lineToedit.Last, newVal)
line(i) = lineToedit
End If
i = i + 1
Next

STAThreadAttribute with SaveFileDialog VB.NET

I have an application to export ListView to Excel sheet , and im trying to do this in background but i have error in SaveFileDialog.showdialog().This is the error :
An exception of type 'System.Threading.ThreadStateException' occurred
in System.Windows.Forms.dll but was not handled in user code
Additional information: Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a debugger is attached to the process.
and this is my code :
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Public Sub saveExcelFile(ByVal FileName As String)
Try
Dim xls As New Excel.Application
Dim sheet As Excel.Worksheet
Dim i As Integer
xls.Workbooks.Add()
sheet = xls.ActiveWorkbook.ActiveSheet
Dim row As Integer = 1
Dim col As Integer = 1
For i = 0 To Me.ListView1.Columns.Count - 1
sheet.Cells(1, i + 1) = Me.ListView1.Columns(i).Text
Next
For i = 0 To Me.ListView1.Items.Count - 1
For j = 0 To Me.ListView1.Items(i).SubItems.Count - 1
sheet.Cells(i + 2, j + 1) = Me.ListView1.Items(i).SubItems(j).Text
Next
Next
row += 1
col = 1
' for the header
sheet.Rows(1).Font.Name = "Cooper Black"
sheet.Rows(1).Font.size = 12
sheet.Rows(1).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter
Dim mycol As System.Drawing.Color = System.Drawing.ColorTranslator.FromHtml("#148cf7")
sheet.Rows(1).Font.color = mycol
' for all the sheet without header
sheet.Range("a2", "z1000").Font.Name = "Arial"
sheet.Range("a2", "z1000").Font.Size = 13
sheet.Range("a2", "z1000").HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter
sheet.Range("A1:X1").EntireColumn.AutoFit()
sheet.Range("A1:X1").EntireRow.AutoFit()
xls.ActiveWorkbook.SaveAs(FileName)
xls.Workbooks.Close()
xls.Quit()
Catch ex As Exception
End Try
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Try
Dim saveFileDialog1 As New SaveFileDialog
saveFileDialog1.Filter = "Excel File|*.xlsx"
saveFileDialog1.Title = "Save an Excel File"
saveFileDialog1.ShowDialog()
If saveFileDialog1.FileName <> "" Then
saveExcelFile(saveFileDialog1.FileName)
End If
Catch ex As Exception
End Try
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MsgBox("done")
End Sub
You could move everything concerning SaveFileDialog1 to Button3_Click and store the filename in a Private variable, so it can be used later in BackgroundWorker1_DoWork.
Private _filename As String
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
SaveFileDialog1.Title = "Save Excel File"
SaveFileDialog1.Filter = "Excel files (*.xls)|*.xls|Excel Files (*.xlsx)|*.xslx"
SaveFileDialog1.ShowDialog()
'exit if no file selected
If SaveFileDialog1.FileName = "" Then
Exit Sub
End If
_filename = SaveFileDialog1.FileName
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
...
book.SaveAs(_filename)
...
End Sub
i put this code in load form and everything is perfect:
Control.CheckForIllegalCrossThreadCalls = False