Dynamic button click event not able to call a function vb.net - vb.net

The TabLoad() function doesn't seem to be working on clicking of this dynamic button. The aim of this button click event is that it deletes text from a text file and loads the form again.
Below is the complete code. The TabLoad() function is in the NextDelbtn_Click sub at the end.
Also any suggestion regarding change of code is appreciated.
Imports System.IO
Public Class Form1
Dim str As String
Dim FILE_NAME As String = "D:\1.txt"
Dim file_exists As Boolean = File.Exists(FILE_NAME)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text = "" Then
MsgBox("Please enter text that you want to save", MsgBoxStyle.Information, "TOCC Error")
Else
str = TextBox1.Text
Dim fs As FileStream = Nothing
If (Not File.Exists(FILE_NAME)) Then
fs = File.Create(FILE_NAME)
Using fs
End Using
End If
If File.Exists(FILE_NAME) Then
Dim sw As StreamWriter
sw = File.AppendText(FILE_NAME)
sw.WriteLine(str)
sw.Flush()
sw.Close()
TabLoad()
TextBox1.Text = ""
End If
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
TabControl1.SelectedIndex = TabControl1.TabIndex + 1
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TabLoad()
End Sub
Private Sub Nextbtn_Click(sender As Object, e As EventArgs)
Dim s As String = DirectCast(DirectCast(sender, Button).Tag, Label).Text
Clipboard.SetText(s)
End Sub
Private Sub TabLoad()
Dim i As Integer = 1
For Each line As String In System.IO.File.ReadAllLines(FILE_NAME)
Dim NextLabel As New Label
Dim Nextbtn As New Button
Dim NextDelbtn As New Button
NextLabel.Text = line
Nextbtn.Text = "Copy"
NextDelbtn.Text = "Delete"
NextLabel.Height = 22
Nextbtn.Width = 55
Nextbtn.Height = 22
NextDelbtn.Width = 55
NextDelbtn.Height = 22
Nextbtn.BackColor = Color.WhiteSmoke
NextLabel.Tag = Nextbtn
Nextbtn.Tag = NextLabel
NextDelbtn.Tag = NextLabel
NextDelbtn.BackColor = Color.WhiteSmoke
NextLabel.BackColor = Color.Yellow
TabPage2.Controls.Add(NextLabel)
TabPage2.Controls.Add(Nextbtn)
TabPage2.Controls.Add(NextDelbtn)
NextLabel.Location = New Point(10, 10 * i + ((i - 1) * NextLabel.Height))
Nextbtn.Location = New Point(120, 10 * i + ((i - 1) * Nextbtn.Height))
NextDelbtn.Location = New Point(180, 10 * i + ((i - 1) * NextDelbtn.Height))
AddHandler Nextbtn.Click, AddressOf Me.Nextbtn_Click
AddHandler NextDelbtn.Click, AddressOf Me.NextDelbtn_Click
i += 1
Next
File.WriteAllLines(FILE_NAME,
File.ReadAllLines(FILE_NAME).Where(Function(y) y <> String.Empty))
End Sub
Private Sub NextDelbtn_Click(sender As Object, e As EventArgs)
Dim btn As Button = CType(sender, Button)
Dim s As String = (btn.Tag).Text
Dim lines() As String = IO.File.ReadAllLines(FILE_NAME)
Using sw As New IO.StreamWriter(FILE_NAME)
For Each line As String In lines
If line = s Then
line = ""
End If
sw.WriteLine(line)
Next
sw.Flush()
sw.Close()
TabLoad()
End Using
End Sub
End Class

Your problem appears to be that you're initializing new controls but you're not changing the controls on the form or even creating a new form.

Related

How to save dynamically added button for next run in vb.net

I have written code to add a button based on the number of buttons the user needs to add to the form. I am having a very difficult time figuring out how to save the buttons that have been added during runtime and have them persist to the next run. I tried using My.Settings, but have had no luck. Any help would be appreciated! Below is the code I am using to add button(s).
Private Sub UploadNew_Click(sender As Object, e As EventArgs) Handles UploadNew.Click
Num = InputBox("How many lines to add?")
Dim pt As Point
pt.X = 9
pt.Y = 67
For x = 1 To Num
DocName = InputBox("What is the name of the document?")
Buttons(x) = New Button
Buttons(x).Location = pt
Buttons(x).Height = 35
Buttons(x).Width = 434
Buttons(x).Text = DocName 'assigned earlier in code
SplitContainer1.Panel1.Controls.Add(Buttons(x))
pt.Y = pt.Y + 43
Next
End Sub
I use the binary serialization. It probably could be done with XML serialization also. The trick is to mark the class as <Serializable>You might think we could just serialize the button but that is not marked as serializable in the framework.
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Public Class SaveDynamicButtons
Private Buttons As New List(Of MyButtonSettings)
Private Sub SaveDynamicButtons_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If Not File.Exists("ButtonList.dat") Then
Exit Sub
End If
Dim myList As List(Of MyButtonSettings)
' 1. Create an instance of Binary Formatter
Dim bf As New BinaryFormatter()
' 2. Get an instance of a FileStream for the OpenRead method of File passing in (the fileName)
Using fs As Stream = File.OpenRead("ButtonList.dat")
'3. cast back to original object, the Deserialize method of the Binary Formatter passing in the File Stream
myList = (CType(bf.Deserialize(fs), List(Of MyButtonSettings)))
End Using
For Each item In myList
Dim btn As New Button
btn.Location = item.Location
btn.Height = 35
btn.Width = 434
btn.Text = item.Text
Me.Controls.Add(btn)
Next
End Sub
Private Sub AddButtons()
Dim Num As Integer
If Not Integer.TryParse(InputBox("How many lines to add?"), Num) Then
MessageBox.Show("Please enter a valid number")
Exit Sub
End If
Dim pt As Point
pt.X = 9
pt.Y = 67
For x = 1 To Num
Dim DocName As String = InputBox("What is the name of the document?")
Dim btn As New Button
Dim myBtn As New MyButtonSettings
btn.Location = pt
myBtn.Location = pt
btn.Height = 35
btn.Width = 434
btn.Text = DocName
myBtn.Text = DocName
Me.Controls.Add(btn)
Buttons.Add(myBtn)
pt.Y = pt.Y + 43
Next
End Sub
Private Sub SaveButtons()
Dim bf As BinaryFormatter = New BinaryFormatter()
'FileStream(FileName, Mode, Access, Share) intellisense overload #9 out of 15
Using fs As Stream = New FileStream("ButtonList.dat", FileMode.Create, FileAccess.Write, FileShare.None)
bf.Serialize(fs, Buttons)
End Using
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
AddButtons()
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
SaveButtons()
End Sub
End Class
<Serializable>
Public Class MyButtonSettings
Public Property Location As Point
Public Property Text As String
End Class

looping to add 271 records into my dictionary it only add 150 then exit the subroutine. (VB.net 2015)

For VB.net 2015
I'm a new programmer. I've been warping my brain around this for 2 days. Can seem to see the problem. It seems I can only add 150 records to the dictionary. I'm not sure where its failing in the code. I'm not getting any errors or warnings.
Really hope someone can give me a hand.
Heres a link to my file I'm working with.
https://drive.google.com/file/d/0B1zf86jcRv49Y1lCMHRvNWt4UFk/view?usp=sharing
P.S. Sry about the crappy coding skill :-)
Imports System
Imports System.IO
Public Class Form1
Dim xx As Integer = 0
Private MainDataList As New Dictionary(Of String, List(Of String))
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim temp1 As List(Of String)
'MsgBox(xx)
If MainDataList.ContainsKey(TextBox1.Text) Then
temp1 = MainDataList.Item(TextBox1.Text)
Label1.Text = temp1(0)
Beep()
Else
Label1.Text = "Not Found"
Beep()
Beep()
End If
TextBox1.Text = ""
End Sub
Private Sub GetData()
Dim ReadDataLine(50000) As String
Try
' Open the file using a stream reader.
Using sr As New StreamReader("C:\Inventory\Invatory.csv")
'Dim line As String
' Read the stream to a string and write the string to the console.
ReadDataLine(0) = sr.ReadLine
Do While (sr.EndOfStream = False)
ReadDataLine(xx) = sr.ReadLine
'AddToList(ReadDataLine) ' pars data into main list
'MsgBox(sr.ReadLine)
xx = xx + 1
Loop
sr.Close()
'line = sr.ReadLine()
End Using
Catch e As Exception
'MsgBox(xx)
MsgBox("The file could not be read:")
MsgBox(e.Message)
End Try
'MsgBox(xx)
'xx = 0
For Each i As String In ReadDataLine
AddToList(i)
'MsgBox(xx)
'xx = xx + 1
Next
End Sub
Private Sub AddToList(data As String)
Dim barCode As String = ""
Dim steps As Integer = 1
Dim LastPos As Integer = 2
Dim datalist As New List(Of String)
Dim firstPass As Boolean = False
For i = 2 To Len(data)
'Find end of cell
If Mid(data, i, 1) = "," Then
If firstPass = False Then
barCode = Mid(data, LastPos, i - 2)
'MsgBox(Mid(data, LastPos, i - 2))
LastPos = i
firstPass = True
Else
Dim temp As Integer = i - LastPos
datalist.Add(Mid(data, LastPos + 1, temp - 1))
'MsgBox(Mid(data, LastPos + 1, temp - 1))
LastPos = i
End If
End If
Next
MainDataList.Add(barCode, datalist)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
GetData()
Label1.Text = "Ready!"
Me.Show()
TextBox1.Focus()
End Sub
Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
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

Error message whenever alphabet is entered rather than number

I m new to vb.net & I have a problem that whenever user enters an alphabet he/she will receive message that only numbers are allowed. For this code.... Please help me. I shall be very thankful to you.
Public Class Form1
Private Sub DataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
If DataGridView1.CurrentCell.ColumnIndex = 0 Then
Dim combo As ComboBox = CType(e.Control, ComboBox)
If (combo IsNot Nothing) Then
RemoveHandler combo.SelectionChangeCommitted, New EventHandler(AddressOf ComboBox_SelectionChangeCommitted)
AddHandler combo.SelectionChangeCommitted, New EventHandler(AddressOf ComboBox_SelectionChangeCommitted)
End If
End If
End Sub
Private Sub ComboBox_SelectionChangeCommitted(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim combo As ComboBox = CType(sender, ComboBox)
If combo.SelectedItem = "Item1" Then
DataGridView1.CurrentRow.Cells(1).Value = "KG"
DataGridView1.CurrentRow.Cells(3).Value = "100"
DataGridView1.CurrentRow.Cells(2).Value = "Raw Material"
ElseIf combo.SelectedItem = "Item2" Then
DataGridView1.CurrentRow.Cells(1).Value = "Liter"
DataGridView1.CurrentRow.Cells(3).Value = "47"
DataGridView1.CurrentRow.Cells(2).Value = "Raw Material"
ElseIf combo.SelectedItem = "Item3" Then
DataGridView1.CurrentRow.Cells(1).Value = "Pound"
DataGridView1.CurrentRow.Cells(3).Value = "54"
DataGridView1.CurrentRow.Cells(2).Value = "Raw Material"
End If
End Sub
Private Sub Mul_Button_Click(sender As Object, e As EventArgs) Handles Mul_Button.Click
Dim s As Int16 = Convert.ToInt16(DataGridView1.CurrentRow.Cells(3).Value)
Dim s1 As Int16 = Convert.ToInt16(DataGridView1.CurrentRow.Cells(4).Value)
DataGridView1.CurrentRow.Cells(5).Value = s * s1
End Sub
Private Sub DataGridView1_CellValidated(sender As Object, e As EventArgs) Handles DataGridView1.CellValidated
Dim s As Int16 = Convert.ToInt16(DataGridView1.CurrentRow.Cells(3).Value)
Dim s1 As Int16 = Convert.ToInt16(DataGridView1.CurrentRow.Cells(4).Value)
DataGridView1.CurrentRow.Cells(5).Value = s * s1
If DataGridView1.RowCount > 0 Then
Dim sum As Integer
For index As Integer = 0 To DataGridView1.RowCount - 1
sum += Convert.ToInt32(DataGridView1.Rows(index).Cells(5).Value)
Next
TextBox1.Text = sum
End If
End Sub
Private Sub Add_Button_Click(sender As Object, e As EventArgs) Handles Add_Button.Click
If DataGridView1.RowCount > 0 Then
Dim sum As Integer
For index As Integer = 0 To DataGridView1.RowCount - 1
sum += Convert.ToInt32(DataGridView1.Rows(index).Cells(5).Value)
Next
TextBox1.Text = sum
End If
End Sub
End Class
Either wrap your code that has Convert.ToInt16() calls in them with Try/Catch blocks, or convert them to the Int16.TryParse() approach instead.
For example, this line:
Dim s As Int16 = Convert.ToInt16(DataGridView1.CurrentRow.Cells(3).Value)
Could become:
Dim s As Int16
Dim strValue As String = DataGridView1.CurrentRow.Cells(3).Value
If Int16.TryParse(strValue, s) Then
' ... do something with "s" in here ...
' ... continue with code...
Else
MessageBox.Show(strValue, "Invalid Value")
End If

How to call a dynamically created label from its associated dynamically created button's click in vb.net

I have a tab in a form. On form load, I am getting text from a text file line by line and displaying them as labels on a form Tabcontrol Tabpage along with dynamically displaying buttons beside them. Now on those buttons click I want to copy the text in the associated labels. Can anyone suggest what to put in the Nextbtn_Click event?
Dim FILE_NAME As String = "D:\1.txt"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim i As Integer = 1
For Each line As String In System.IO.File.ReadAllLines(FILE_NAME)
Dim NextLabel As New Label
Dim Nextbtn As New Button
NextLabel.Text = line
Nextbtn.Text = "Copy"
NextLabel.Height = 22
Nextbtn.Width = 55
Nextbtn.Height = 22
NextLabel.BackColor = Color.Yellow
TabPage2.Controls.Add(NextLabel)
TabPage2.Controls.Add(Nextbtn)
NextLabel.Location = New Point(10, 10 * i + ((i - 1) * NextLabel.Height))
Nextbtn.Location = New Point(120, 10 * i + ((i - 1) * Nextbtn.Height))
AddHandler Nextbtn.Click, AddressOf Me.Nextbtn_Click
i += 1
Next
End Sub
Private Sub Nextbtn_Click(sender As Object, e As EventArgs)
End Sub
Store the assc. label in the tag property and you can cast it back when you click on the button. The sender object is the button that is currently clicked.
Dim FILE_NAME As String = "D:\1.txt"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim i As Integer = 1
For Each line As String In System.IO.File.ReadAllLines(FILE_NAME)
Dim NextLabel As New Label
Dim Nextbtn As New Button
Nextbtn.Tag = NextLabel
NextLabel.Text = line
Nextbtn.Text = "Copy"
NextLabel.Height = 22
Nextbtn.Width = 55
Nextbtn.Height = 22
NextLabel.BackColor = Color.Yellow
TabPage2.Controls.Add(NextLabel)
TabPage2.Controls.Add(Nextbtn)
NextLabel.Location = New Point(10, 10 * i + ((i - 1) * NextLabel.Height))
Nextbtn.Location = New Point(120, 10 * i + ((i - 1) * Nextbtn.Height))
AddHandler Nextbtn.Click, AddressOf Me.Nextbtn_Click
i += 1
Next
End Sub
Private Sub Nextbtn_Click(sender As Object, e As EventArgs)
Dim s As String = DirectCast(DirectCast(sender, Button).Tag, Label).Text
End Sub
Private Sub Clicked(ByVal sender As Object, ByVal e As EventArgs)
Dim b As Button = DirectCast(sender, Button)
TextBox2.Text = b.Name
Clipboard.SetText(b.Name)
End Sub