Save TreeView As TXT or XML - vb.net

Is there a way to save all the treeview items in visual basic as an TXT file (I Prefer TXT) or XML?
I also want to save it to my.settings.

Use a recursive function e.g.
Public Class Form1
Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
TreeView1.Nodes.Add("Animal")
TreeView1.Nodes(0).Nodes.Add("Reptile")
TreeView1.Nodes(0).Nodes(0).Nodes.Add("Dragon")
TreeView1.Nodes(0).Nodes(0).Nodes.Add("Lizard")
TreeView1.Nodes(0).Nodes.Add("Mammal")
TreeView1.Nodes(0).Nodes(1).Nodes.Add("Cat")
TreeView1.Nodes(0).Nodes(1).Nodes.Add("Dog")
TreeView1.Nodes.Add("Vegetable")
TreeView1.Nodes(1).Nodes.Add("Fruit")
TreeView1.Nodes(1).Nodes(0).Nodes.Add("Apple")
TreeView1.Nodes(1).Nodes(0).Nodes.Add("Orange")
TreeView1.Nodes(1).Nodes(0).Nodes.Add("Pear")
TreeView1.Nodes(1).Nodes.Add("Aubergine")
TreeView1.Nodes(1).Nodes.Add("Carrot")
TreeView1.Nodes(1).Nodes.Add("Cucumber")
TreeView1.Nodes(1).Nodes.Add("Zucchini")
TreeView1.Nodes.Add("Mineral")
TreeView1.Nodes(2).Nodes.Add("Granite")
TreeView1.Nodes(2).Nodes.Add("Quartz")
TreeView1.Nodes(2).Nodes.Add("Topaz")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox1.Multiline = True
TextBox1.Height = 200
TextBox1.Width = 200
TextBox1.Text = WriteTreeView("", TreeView1.Nodes)
End Sub
Private Function WriteTreeView(ByVal parent As String, ByVal tnc As TreeNodeCollection) As String
Dim strOutput As String = ""
If tnc.Count = 0 Then
strOutput = parent & vbCrLf 'leaf
Else
For i As Integer = 0 To tnc.Count - 1
Dim strCurrent As String = ""
If parent > "" Then strCurrent = parent & "."
strCurrent &= tnc(i).Text
strOutput &= WriteTreeView(strCurrent, tnc(i).Nodes)
Next i
End If
Return strOutput
End Function
End Class

Related

Displaying file properties

Is possible to display file properties with full path and date. I would like to add file size and/or hash value of the file to the output (if possible) the data will be written to a text file not done yet I want to get the basic operation working first. This will be used as a file monitor for USB drives when all is said and done.
Imports System.IO
Public Class Form1
Inherits System.Windows.Forms.Form
Private WithEvents objWatcher As New clsFSW()
#Region " Windows Form Designer generated code "
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
'Add any initialization after the InitializeComponent() call
End Sub
'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
Friend WithEvents cmdStart As System.Windows.Forms.Button
Friend WithEvents cmdStop As System.Windows.Forms.Button
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents txtFolder As System.Windows.Forms.TextBox
Friend WithEvents chkSubFolders As System.Windows.Forms.CheckBox
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.TextBox1 = New System.Windows.Forms.TextBox()
Me.cmdStart = New System.Windows.Forms.Button()
Me.cmdStop = New System.Windows.Forms.Button()
Me.Label1 = New System.Windows.Forms.Label()
Me.txtFolder = New System.Windows.Forms.TextBox()
Me.chkSubFolders = New System.Windows.Forms.CheckBox()
Me.SuspendLayout()
'
'TextBox1
'
Me.TextBox1.Location = New System.Drawing.Point(32, 8)
Me.TextBox1.Multiline = True
Me.TextBox1.Name = "TextBox1"
Me.TextBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical
Me.TextBox1.Size = New System.Drawing.Size(392, 240)
Me.TextBox1.TabIndex = 0
Me.TextBox1.Text = ""
'
'cmdStart
'
Me.cmdStart.Location = New System.Drawing.Point(120, 336)
Me.cmdStart.Name = "cmdStart"
Me.cmdStart.TabIndex = 1
Me.cmdStart.Text = "Start Watch"
'
'cmdStop
'
Me.cmdStop.Location = New System.Drawing.Point(216, 336)
Me.cmdStop.Name = "cmdStop"
Me.cmdStop.TabIndex = 2
Me.cmdStop.Text = "Stop Watch"
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Location = New System.Drawing.Point(6, 272)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(93, 13)
Me.Label1.TabIndex = 3
Me.Label1.Text = "Folder to Monitor:"
'
'txtFolder
'
Me.txtFolder.Location = New System.Drawing.Point(110, 272)
Me.txtFolder.Name = "txtFolder"
Me.txtFolder.Size = New System.Drawing.Size(184, 20)
Me.txtFolder.TabIndex = 4
Me.txtFolder.Text = ""
'
'chkSubFolders
'
Me.chkSubFolders.Location = New System.Drawing.Point(312, 272)
Me.chkSubFolders.Name = "chkSubFolders"
Me.chkSubFolders.Size = New System.Drawing.Size(128, 24)
Me.chkSubFolders.TabIndex = 6
Me.chkSubFolders.Text = "Include Subfolders"
'
'Form1
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(464, 373)
Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.chkSubFolders, Me.txtFolder, Me.Label1, Me.cmdStop, Me.cmdStart, Me.TextBox1})
Me.Name = "Form1"
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.Text = "File System Watcher Class Demo"
Me.ResumeLayout(False)
End Sub
#End Region
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cmdStop.Enabled = False
With objWatcher
End With
End Sub
Private Sub cmdStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdStart.Click
Dim sDir As String
sDir = txtFolder.Text
If IO.Directory.Exists(sDir) Then
objWatcher.FolderToMonitor = sDir
objWatcher.StartWatch()
cmdStop.Enabled = True
cmdStart.Enabled = True
chkSubFolders.Enabled = True
Else
MessageBox.Show("Folder does not exist!")
End If
End Sub
Private Sub cmdStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdStop.Click
objWatcher.StopWatch()
cmdStop.Enabled = True
cmdStart.Enabled = True
chkSubFolders.Enabled = True
End Sub
Private Sub chkSubFolders_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkSubFolders.CheckedChanged
objWatcher.IncludeSubfolders = (chkSubFolders.Checked = True)
End Sub
Private Sub objWatcher_FileCreated(ByVal FullPath As String) Handles objWatcher.FileCreated
TextBox1.Text &= "File Created: " & FullPath & ", " & DateString & vbCrLf
End Sub
Private Sub objWatcher_FileChanged(ByVal FullPath As String) Handles objWatcher.FileChanged
TextBox1.Text &= "File Changed: " & FullPath & ", " & DateString & vbCrLf
End Sub
Private Sub objWatcher_FileDeleted(ByVal FullPath As String) Handles objWatcher.FileDeleted
TextBox1.Text &= "File Deleted: " & FullPath & ", " & DateString & vbCrLf
End Sub
Private Sub objWatcher_FileRenamed(ByVal OldFileName As String, ByVal newFileName As String) Handles objWatcher.FileRenamed
TextBox1.Text &= "File Rename: " & OldFileName & " to " & newFileName & ", " & DateString & vbCrLf
End Sub
Private Sub objWatcher_FileWatchError(ByVal ErrMsg As String) Handles objWatcher.FileWatchError
TextBox1.Text &= "The following error occurred: " & ErrMsg & vbCrLf
End Sub
End Class

How to pass all value of ListBox Control to a function?

I am writing a simple application to read the value a textbox and add to a listbox control . But i have to pass the listbox control to function . Any suggestion ?
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
test("E:\Satyajit.txt")
End Sub
Public Function test(ByVal filename As String)
Dim FILE_NAME As String = filename
Dim TextLine As String
Dim result As String = Path.GetFileName(FILE_NAME)
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
words = TextLine.Split(New Char() {","c})
ListBox1.Items.Add(words(3) & "," & words(4))
objItem = ListView1.Items.Add(words(3) & "," & words(4))
Loop
test1(ListBox1.Items)//pass the listbox value hare
End Function
Public Function test1(ByVal value As String)
Dim Fest As String = value
MsgBox(Fest)
End Function
You're passing the contents of a ListBox to a method that is just displaying them in a MsgBox(). There are two approaches you can do to accomplish what I think you're wanting.
You can pass ListBox.Items to the method and iterate through each item concatenating them into a single String or StringBuilder, then pass the String to the MsgBox(). This approach makes your method dependent on ListBoxItems.
You can iterate through ListBox.Items concatenating them into a single String or StringBuilder, then pass the String to your method. This makes your method a little more scalable.
I recommend approach #2, something like:
Dim MyListBox As New ListBox
MyListBox.Items.Add("Item1")
MyListBox.Items.Add("Item2")
MyListBox.Items.Add("Item3")
MyListBox.Items.Add("Item4")
MyListBox.Items.Add("Item5")
Dim sb As New StringBuilder
For Each Item In MyListBox.Items
sb.AppendLine(Item)
Next
Test1(sb.ToString())
The Test1 method would look like:
Public Sub Test1(ByVal value As String)
MsgBox(value)
End Sub
Results:
You could pass the whole control to the function:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim lstbox As New ListBox
lstbox.Items.Add("Hello")
lstbox.Items.Add("Second Item")
lstbox.Items.Add("Third Item")
MsgBox("The list contains: " & Length(lstbox) & " characters")
End Sub
Function Length(ByVal ctrl As ListBox) As Integer
Dim TotalNumberOfItems As Integer = 0
For Each item As String In ctrl.Items.ToString
TotalNumberOfItems += 1
Next
Return TotalNumberOfItems
End Function
or just its items
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim lstbox As New ListBox
lstbox.Items.Add("Hello")
lstbox.Items.Add("Second Item")
lstbox.Items.Add("Third Item")
MsgBox("The list contains: " & Length(lstbox.Items) & " characters")
End Sub
Function Length(ByVal col As ListBox.ObjectCollection) As Integer
Dim TotalNumberOfCharacters As Integer = 0
For Each item As String In col
TotalNumberOfCharacters += item.Length
Next
Return TotalNumberOfCharacters
End Function

Vb.net Save data from datagridview to txt and load it

i'am new programmer and just studying about Visual Basic, and to complete my exams
The Data i have
Tool_1 screwdriver
Tool_2 screw
Tool_3 Magnet
And many more
i've create project, it have Data Grid View(two columns, Tools & Names) and two Button(btSave & btOpen)
i just try it with this code
Private Sub btSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btSave.Click
SaveGridData(DataGridView1, ThisFilename)
End Sub
Private Sub SaveGridData(ByRef ThisGrid As DataGridView, ByVal Filename As String)
ThisGrid.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText
ThisGrid.SelectAll()
IO.File.WriteAllText(Filename, ThisGrid.GetClipboardContent().GetText.TrimEnd)
ThisGrid.ClearSelection()
End Sub
Private Sub btOpen_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btOpen.Click
LoadGridData(DataGridView1, ThisFilename)
End Sub
Private Sub LoadGridData(ByRef ThisGrid As DataGridView, ByVal Filename As String)
ThisGrid.Rows.Clear()
For Each THisLine In My.Computer.FileSystem.ReadAllText(Filename).Split(Environment.NewLine)
ThisGrid.Rows.Add(Split(THisLine, " "))
Next
End Sub
When i save the file it's no problem the txt file is ok, but when i want to load Text "Tool_1 Screwdriver" is not split but is in "Tools" Column
there is a solution to this ?
use this insetad of your loop in loadgriddata
For Each THisLine In My.Computer.FileSystem.ReadAllText(Filename).Split(Environment.NewLine)
dim str as string()
str=thisline.split(" ")
ThisGrid.Rows.Add(str(0),str(1))
Next
hope it helps.
Hey I struggled with this aswell, but I have some usefull code:
export listview:
System.IO.Directory.CreateDirectory("C:\RS Account Maker\Accounts" & "\")
SaveFileDialog1.ShowDialog()
Dim Path As String = SaveFileDialog1.FileName
Dim AllItems As String = ""
Try
For Each item As ListViewItem In ListView1.Items
AllItems = AllItems & item.Text & "#" & item.SubItems(1).Text & "#" & item.SubItems(2).Text & vbNewLine
Next
AllItems = AllItems.Trim
Catch ex As Exception
End Try
Try
If My.Computer.FileSystem.FileExists(Path) Then
My.Computer.FileSystem.DeleteFile(Path)
End If
My.Computer.FileSystem.WriteAllText(Path, AllItems, False)
Catch ex As Exception
MsgBox("Error" & vbNewLine & ex.Message, MsgBoxStyle.Exclamation, "Error ")
End Try
import listview:
OpenFileDialog1.ShowDialog()
Dim Path As String = OpenFileDialog1.FileName
Dim AllItems As String
Try
AllItems = My.Computer.FileSystem.ReadAllText(Path)
Dim ItemLines As New TextBox
ItemLines.Text = AllItems
For Each line As String In ItemLines.Lines
Dim a1() As String = line.Split("#")
Dim ItemName As String = a1(0)
Dim SubItem1 As String = a1(1)
Dim SubItem2 As String = a1(2)
Dim Item As New ListViewItem(ItemName)
Item.SubItems.Add(SubItem1)
Item.SubItems.Add(SubItem2)
ListView1.Items.AddRange(New ListViewItem() {Item})
Next
Catch ex As Exception
MsgBox("Error" & vbNewLine & ex.Message, MsgBoxStyle.Exclamation, "Error ")
End Try
The following line is wrong.
ThisGrid.Rows.Add(Split(THisLine, " "))
The above code was amended as follows.
Dim ThisFilename As String = Application.StartupPath & "\MyData.dat"
Private Sub butSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
SaveGridData(Datagrid1, ThisFilename)
End Sub
Private Sub butLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
LoadGridData(Datagrid1, ThisFilename)
End Sub
Private Sub SaveGridData(ByRef ThisGrid As DataGridView, ByVal Filename As String)
ThisGrid.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText
ThisGrid.SelectAll()
IO.File.WriteAllText(Filename, ThisGrid.GetClipboardContent().GetText.TrimEnd)
ThisGrid.ClearSelection()
End Sub
Private Sub LoadGridData(ByRef ThisGrid As DataGridView, ByVal Filename As String)
ThisGrid.Rows.Clear()
For Each THisLine In My.Computer.FileSystem.ReadAllText(Filename).Split(Environment.NewLine)
ThisGrid.Rows.Add(Split(THisLine, ControlChars.Tab))
Next
End Sub

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

Variable 'details' is used before it has been assigned a value.

Variable details is used before it has been assigned a value. What is the problem with details?
Option Explicit On
Imports System.Text
Imports System.IO
Public Class Main
Private SelectedItem As ListViewItem
Dim data As String
Dim strpriority As String
Dim task As String
Dim createdate As String
Dim duedate As String
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
AddTask.Show()
Me.Hide()
End Sub
Private Sub HistoryToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HistoryToolStripMenuItem.Click
History.Show()
Me.Hide()
End Sub
Private Sub Main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim fpath As String
Dim splitdata
fpath = AppDomain.CurrentDomain.BaseDirectory
Dim filepath As String
filepath = fpath & "task.txt"
Dim details As String
details = My.Computer.FileSystem.ReadAllText(filepath)
splitdata = Split(details, vbCrLf)
Dim i As Integer
For i = 0 To UBound(splitdata)
lblTaskName.Items.Add(splitdata(i))
Next
lblTime.Enabled = True
Timer1.Interval = 10
Timer1.Enabled = True
lblDate.Text = DateTime.Now.ToString("dd MMMM yyyy")
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
lblTime.Text = TimeOfDay
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
End
End Sub
Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemove.Click
If lblTaskName.SelectedItem = "" Then
MsgBox("Please select a record")
Else
If lblTaskName.Items.Count > 0 Then
If MessageBox.Show("Do you really want to delete this record?", "Delete", MessageBoxButtons.YesNo) = MsgBoxResult.Yes Then
lblTaskName.Items.Remove(lblTaskName.SelectedItem.ToString())
Else
MessageBox.Show("Operation Cancelled")
End If
End If
End If
Try
Dim fpath As String
fpath = AppDomain.CurrentDomain.BaseDirectory
Dim filepath As String
filepath = fpath & "task.txt"
Dim details As String
If lblTaskName.Items.Count > 0 Then
details = lblTaskName.Items(0)
Dim i As Integer
For i = 1 To lblTaskName.Items.Count - 1
details = details & vbCrLf & lblTaskName.Items(i)
Next
End If
My.Computer.FileSystem.WriteAllText(filepath, details, False)
Catch ex As Exception
MsgBox("Values Can't be inserted this time")
End Try
End Sub
Private Function filepaths() As String
Throw New NotImplementedException
End Function
End Class
The problem is in the btnRemove_Click method in this part:
Dim details As String
If lblTaskName.Items.Count > 0 Then
details = lblTaskName.Items(0)
If the condition evaluates to false, the details variable is used before it is initialized, because it is only set in the if block up to now.
I suppose you want to move the following line into the if block to solve the problem:
My.Computer.FileSystem.WriteAllText(filepath, details, False)
Alternatively, you can come up with a default value for details so that it is set in any case. For performance reasons, you can set the default value (e.g. a text or String.Empty) in an else branch:
Dim details As String
If lblTaskName.Items.Count > 0 Then
' ...
Else
details = "Default Value"
End If
You need to think through the flow of your program. Consider this code:
Dim details As String
If lblTaskName.Items.Count > 0 Then
details = lblTaskName.Items(0)
Dim i As Integer
For i = 1 To lblTaskName.Items.Count - 1
details = details & vbCrLf & lblTaskName.Items(i)
Next
End If
My.Computer.FileSystem.WriteAllText(filepath, details, False)
You declare the details variable at the top. Then you check that there is at least 1 item in the lblTaskName control. If that test passes, then you assign the first item to details. But what if that test doesn't pass? What if there are 0 items in the lblTaskName control? In that case, the interior of the If block never runs, and nothing ever gets stored in details. Then in the final line, you try to use the value of the details variable *outside of the If block. This is illegal because it may not have been assigned a value.
Perhaps you meant for that WriteAllText line to be inside of If block? Otherwise, you'll need to add an Else clause to your If statement to handle the case where there are 0 items in lblTaskName.
Aside from that, stylistically speaking, you should prefer to initialize variables at the time of declaration whenever possible. So for example, instead of writing:
Dim fpath As String
Dim splitdata
fpath = AppDomain.CurrentDomain.BaseDirectory
Dim filepath As String
filepath = fpath & "task.txt"
Dim details As String
details = My.Computer.FileSystem.ReadAllText(filepath)
splitdata = Split(details, vbCrLf)
write it as:
Dim fpath As String = AppDomain.CurrentDomain.BaseDirectory
Dim filepath As String = fpath & "task.txt"
Dim details As String = My.Computer.FileSystem.ReadAllText(filepath)
Dim splitdata() As String = Split(details, vbCrLf)
(I'm OCD, so I line up my equals signs. That part is totally optional.)
It doesn't make the code run any faster, but it does make it easier to read! More importantly, it decreases the potential for bugs.