How to save dynamically added button for next run in vb.net - 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

Related

snap to grid MDI child forms vb.net

I'm developping a modular dashboard in Visual Basic that starts as an empty container than i can add modules to populate it.
The parent form is an MDI container and every module is a child MDI form that have fixed size.
I'd like to snap all of that child form to a grid both when the user creates a new one and when moves one of it inside the container (like they are magnetized to that grid).
How can i do that? Thanks
If I well understand you need something like this:
Private Class ImaginaryGrid
' You can change Columns and Rows as you want
Shared Rows As Integer = 3
Shared Cols As Integer = 3
Private Shared Function SnapToGrid(target As Form) As Point
Dim AllW As Integer = Screen.PrimaryScreen.WorkingArea.Width
Dim AllH As Integer = Screen.PrimaryScreen.WorkingArea.Height
Dim parent = target.MdiParent
If parent IsNot Nothing Then
AllW = target.MdiParent.ClientSize.Width
AllH = target.MdiParent.ClientSize.Height
End If
Dim currentPoint As Point = target.Location
Dim stepW As Integer = CInt(AllW / Cols)
Dim stepH As Integer = CInt(AllH / Rows)
Dim targetCol As Integer = CInt(currentPoint.X \ stepW)
Dim targetRow As Integer = CInt(currentPoint.Y \ stepH)
Dim newX As Integer = targetCol * stepW
Dim newY As Integer = targetRow * stepH
target.Location = New Point(newX, newY)
target.Width = stepW
target.Height = stepH
End Function
Shared Sub AttachFormToStayInGrid(frm As Form)
AddHandler frm.ResizeEnd, Sub()
SnapToGrid(frm)
End Sub
SnapToGrid(frm)
End Sub
End Class
Usage:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
ImaginaryGrid.AttachFormToStayInGrid(Me)
End Sub
Take changes (if needed) as comments below shows:
Here's a beefed up version based on the same idea as G3nt_M3caj's suggestion:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ImaginaryGrid.Client = Me.Controls.OfType(Of MdiClient).FirstOrDefault
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim frm As New Form
ImaginaryGrid.AttachFormToStayInGrid(frm)
End Sub
Private Class ImaginaryGrid
Public Shared WithEvents Client As MdiClient
Public Shared FixedChildSize As New Size(250, 150)
Private Shared Function SnapToGrid(target As Form) As Rectangle
Dim colX As Integer = target.Location.X / FixedChildSize.Width
Dim colY As Integer = target.Location.Y / FixedChildSize.Height
Dim newX As Integer = colX * FixedChildSize.Width
Dim newY As Integer = colY * FixedChildSize.Height
Return New Rectangle(New Point(newX, newY), FixedChildSize)
End Function
Shared Sub AttachFormToStayInGrid(frm As Form)
frm.Size = FixedChildSize
frm.FormBorderStyle = FormBorderStyle.FixedSingle
frm.MdiParent = Client.Parent
frm.Show()
SnapChild(frm)
AddHandler frm.ResizeEnd, Sub()
SnapChild(frm)
End Sub
AddHandler frm.LocationChanged, Sub()
If frm.WindowState = FormWindowState.Normal Then
snapRectangle = SnapToGrid(frm)
Client.Refresh()
End If
End Sub
End Sub
Private Shared Sub SnapChild(ByVal frm As Form)
If frm.WindowState = FormWindowState.Normal Then
Dim rc As Rectangle = SnapToGrid(frm)
frm.Bounds = rc
snapRectangle = Nothing
Client.Refresh()
End If
End Sub
Private Shared snapRectangle? As Rectangle
Private Shared Sub Client_Paint(sender As Object, e As PaintEventArgs) Handles Client.Paint
If snapRectangle.HasValue Then
e.Graphics.DrawRectangle(Pens.Black, snapRectangle)
End If
End Sub
End Class
End Class

Shuffle the contents of Text Boxes

I'm trying to get 10 different inputs in TextBoxes to be displayed in a randomized order.
I split 2 processes to make it easier to understand:
Button puts numbers in random orders from 1-10(works)
Button should replace the numbers with the contents of the TextBoxes(doesn't work)
Here is the GUI
/ Here is the code:
Public tblRandom As New DataTable
Private Sub btnRandom_Click(sender As Object, e As EventArgs) Handles btnGo.Click
Dim r As New Random
Dim tblRandom As New DataTable
tblRandom.Columns.Add("Order")
tblRandom.Constraints.Add("pk", tblRandom.Columns(0), True)
While tblRandom.Rows.Count < 10
Dim newrow As Object = r.Next(10) + 1
Try
tblRandom.Rows.Add(CStr(newrow))
Catch ex As Exception
End Try
End While
dgvRandom.DataSource = tblRandom
End Sub
Private Sub btnReplace_Click(sender As Object, e As EventArgs) Handles btnReplace.Click
For Each row As DataGridViewRow In dgvRandom.Rows
For Each cell As DataGridViewCell In row.Cells
If cell.Value IsNot Nothing Then
Dim i As Integer = 0
While i < 10
i += 1
If cell.Value.ToString = i Then
cell.Value = ActiveControl.Tag(i)
End If
End While
End If
Next
Next
dgvRandom.DataSource = tblRandom
End Sub
End Class
My understanding of your goal here is to take the text in 10 textboxes and shuffled their content. The DataGrid seems to be a temporary location that you're using during the shuffle.
There's a much easier way that avoids all that. Try this code:
Private _random = New Random()
Private Sub BtnRandom_Click(sender As Object, e As EventArgs) Handles btnRandom.Click
Dim tbs As TextBox() = {TextBox1, TextBox2, TextBox3, TextBox4, TextBox5, TextBox6, TextBox7, TextBox8, TextBox9, TextBox10}
Dim text = tbs.Select(Function(tb) tb.Text).OrderBy(Function(t) _random.Next()).ToList()
For Each x In tbs.Zip(text, Function(tb, t) New With {.tb = tb, .t = t})
x.tb.Text = x.t
Next
End Sub
That's it. Job done.
If you still need the DataGrid it would be easy to add a further line just after the x.tb.Text = x.t that adds the content of x.t to the grid.
For the first part you can do:
Public tblRandom As DataTable
Private ReadOnly rand As New Random
Private Sub btnRandom_Click(sender As Object, e As EventArgs) Handles btnRandom.Click
tblRandom?.Dispose()
tblRandom = New DataTable
tblRandom.Columns.Add("Order")
tblRandom.Constraints.Add("pk", tblRandom.Columns(0), True)
Dim nums As New List(Of Integer)
While nums.Count < 10
Dim num = rand.Next(1, 11)
If Not nums.Contains(num) Then
nums.Add(num)
End If
End While
nums.ForEach(Sub(n) tblRandom.Rows.Add(n))
dgvRandom.DataSource = tblRandom
End Sub
As for the second part, you just need to do:
Private Sub btnReplace_Click(sender As Object, e As EventArgs) Handles btnReplace.Click
For Each row As DataRow In tblRandom.Rows
'Assuming the text boxes are hosted by the Form.
Dim txt = Me.Controls.OfType(Of TextBox).
Where(Function(x) x.Tag?.ToString = row(0).ToString).
FirstOrDefault
If txt IsNot Nothing Then
row(0) = txt.Text
End If
Next
tblRandom.AcceptChanges()
End Sub
You are getting the tag from the ActiveControl
cell.Value = ActiveControl.Tag(i)
but as you've just clicked the Replace button, isn't that the active control?

Type Text Directly On A Bitmap Image at Mouse Position

I am trying to write (type) directly onto a bitmap. I need to be able to type at the mouse position, so where ever on the screen i click the mouse, I can start typing text with the keyboard.
Here is a working VS 2017 VB Win Form code that will print "Hello World" at the mousedown position. But it only works with predetermined text. I would like to be able to just type at that spot. I feel I am so close, just can't get it to work.
Imports System.IO
Imports System.Windows.Forms.DataVisualization.Charting
Public Class Form1
Dim WithEvents Chart1 As New Chart
Private Structure TextPoints
Dim MPos As Point
Dim Txt As String
End Structure
Private TextList As New List(Of TextPoints)
Private TempPoint As Point
Private FirstPoint As Point
Dim xcnt As Integer = -1
Dim ycnt As Integer = -1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.Size = New Size(1100, 700)
Me.Location = New Point(10, 10)
MakeBackImage()
With Chart1
.Name = "Chart1"
.Location = New System.Drawing.Point(40, 40)
.Size = New System.Drawing.Size(1010, 610)
.BackImage = "BackImg.jpg"
.Parent = Me
End With
End Sub
Private Sub Chart1_MouseDown(ByVal sender As Object,
ByVal e As System.Windows.Forms.MouseEventArgs) _
Handles Chart1.MouseDown
FirstPoint = New Point(e.X, e.Y)
TempPoint = New Point(e.X, e.Y)
Me.Refresh()
End Sub
Private Sub Chart1_MouseUp(ByVal sender As Object,
ByVal e As System.Windows.Forms.MouseEventArgs) _
Handles Chart1.MouseUp
Dim T As New TextPoints With {
.MPos = TempPoint,
.Txt = "Hello World"}
TextList.Add(T)
Me.Refresh()
End Sub
Private Sub MakeBackImage()
Dim x, y As Integer
Dim img As Image = New Bitmap(1020, 620)
Dim graphics As Graphics = Graphics.FromImage(img)
graphics.Clear(Drawing.Color.White)
For x = 0 To 1000 Step 20
graphics.DrawLine(Pens.Black, x, 0, x, 600)
xcnt += 1
Next
For y = 0 To 600 Step 20
ycnt += 1
graphics.DrawLine(Pens.Black, 0, y, 1000, y)
Next
img.Save("BackImg.jpg", Imaging.ImageFormat.Jpeg)
End Sub
Private Sub Chart1_Paint(ByVal sender As Object,
ByVal e As System.Windows.Forms.PaintEventArgs) _
Handles Chart1.Paint
Dim drawString As String = "Hello World"
Dim drawFont As New Font("Arial", 14)
Dim drawBrush As New SolidBrush(Color.Black)
For Each t As TextPoints In TextList
e.Graphics.DrawString(t.Txt, drawFont,
drawBrush, t.MPos.X, t.MPos.Y)
Next
End Sub
End Class
This is a simplified code. Actually, the background image is only created once, but I added code to dynamically create it here to make the demo better.

Dynamic button click event not able to call a function 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.

How to find and update a matching control once a file exists

I have written a WinForm project which displays a ListBox containing a list of file names. When the user clicks a submit button, the application dynamically loads and displays one PictureBox control for each file and then waits while they are processed. As PDF files are generated for each one, the matching PictureBox for that file needs to be updated to display an image.
Here's what I have so far:
Private Sub ButtonSubmit_Click(sender As System.Object, e As System.EventArgs) Handles ButtonSubmit.Click
Dim x As Integer = 790
Dim y As Integer = 91
For i As Integer = 0 To ListBox1.Items.Count - 1
Dim key As String = ListBox1.Items(i).ToString()
'adds picturebox for as many listbox items added
Dim MyPictureBox As New PictureBox()
MyPictureBox.Name = "pic" + key
MyPictureBox.Location = New Point(x, y)
MyPictureBox.Size = New Size(12, 12)
MyPictureBox.SizeMode = PictureBoxSizeMode.StretchImage
Me.Controls.Add(MyPictureBox)
MyPictureBox.Image = My.Resources.Warning1
ToolTipSpooling.SetToolTip(MyPictureBox, "Creating PDF...")
x += 0
y += 13
Next i
Call CheckPDFs()
End Sub
Public Sub CheckPDFs()
Dim ListboxTicketIDs = (From i In ListBox1.Items).ToArray()
For Each Item In ListboxTicketIDs
Dim ID = Item.ToString
Dim Watcher As New FileSystemWatcher()
Watcher.Path = "C:\Temp\"
Watcher.NotifyFilter = (NotifyFilters.Attributes)
Watcher.Filter = ID + ".pdf"
AddHandler Watcher.Changed, AddressOf OnChanged
Watcher.EnableRaisingEvents = True
Next
End Sub
Private Sub OnChanged(source As Object, e As FileSystemEventArgs)
Dim p As PictureBox = CType(Me.Controls("pic" + ListBox1.Items.ToString()), PictureBox)
p.Image = My.Resources.Ok1
End Sub
I'm having trouble changing the PictureBox to a different picture once the item(s) listed in the listbox are present, based on the FileSystemWatcher. For instance, the files are not always created in the same order as they exist in the ListBox.
EDIT
Working code below.
Public Class Form1
Private WithEvents Watcher As FileSystemWatcher
Public Sub CheckPDFs()
For i As Integer = 0 To ListBox1.Items.Count - 1
Watcher = New FileSystemWatcher()
Watcher.SynchronizingObject = Me
Watcher.Path = "C:\Temp\"
Watcher.NotifyFilter = NotifyFilters.Attributes
Watcher.Filter = "*.pdf"
Watcher.EnableRaisingEvents = True
Next
End Sub
Private Sub Watcher_Changed(ByVal sender As Object, ByVal e As FileSystemEventArgs) Handles Watcher.Changed
Dim key As String = Path.GetFileNameWithoutExtension(e.Name)
Dim p As PictureBox = CType(Me.Controls("pic" + key), PictureBox)
p.Image = My.Resources.Ok
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
ListBox1.Items.Add(TextBox1.Text)
TextBox1.Text = ""
Dim x As Integer = 5
Dim y As Integer = 5
For i As Integer = 0 To ListBox1.Items.Count - 1
Dim key As String = ListBox1.Items(i).ToString()
'adds picturebox for as many listbox items added
Dim MyPictureBox As New PictureBox()
MyPictureBox.Name = "pic" + key
MyPictureBox.Location = New Point(x, y)
MyPictureBox.Size = New Size(15, 15)
MyPictureBox.SizeMode = PictureBoxSizeMode.StretchImage
Me.Controls.Add(MyPictureBox)
MyPictureBox.Image = My.Resources.Info
x += 0
y += 18
Next i
Call CheckPDFs()
End Sub
First of all, you don't need to create multiple file watchers. You just need a single file watcher to watch for any changes to the folder. I would recommend declaring it as a private field at the top of your form using the WithEvents keyword so you don't have to worry about adding and removing event handlers.
Next, when the watcher raises the changed event, you can get the file name of the file that changed by looking at the properties of the event args object. You need to get the name of the file that changed and then use the file name as the key to finding the matching picture box control.
Public Class Form1
Private WithEvents Watcher As FileSystemWatcher
Public Sub CheckPDFs()
Watcher = New FileSystemWatcher()
Watcher.Path = "C:\Temp\"
Watcher.NotifyFilter = NotifyFilters.Attributes
Watcher.Filter = "*.pdf"
End Sub
Private Sub Watcher_Changed(ByVal sender As Object, ByVal e As FileSystemEventArgs) Handles Watcher.Changed
Dim key As String = Path.GetFileNameWithoutExtension(e.Name)
Dim p As PictureBox = CType(Me.Controls("pic" + key), PictureBox)
p.Image = My.Resources.Ok1
End Sub
End Class
However, since you say in a comment below that the file name will not be the same as the text in the listbox, but that it will merely start with that text, you could do something like this, instead:
Private Sub Watcher_Changed(ByVal sender As Object, ByVal e As FileSystemEventArgs) Handles Watcher.Changed
Dim p As PictureBox = Nothing
For Each item As Object In ListBox1.Items
If e.Name.StartsWith(item.ToString()) Then
p = CType(Me.Controls("pic" + item.ToString()), PictureBox)
Exit For
End If
Next
If p IsNot Nothing Then
p.Image = My.Resources.Ok1
End If
End Sub