VB: adding object to a tabcontrol tab which doiesnt exist at this time - vb.net

i want to add a tabcontrol tab by pressing on a button:
Dim inp As String
inp = TextBox6.Text
TabControl2.TabPages.Add(inp)
and when i open this tabpage some object should be already created like a button and a textbox, etc.
i havent found any type of onload events for a tabpage so i tried to add this with:
TabPage8.Controls.Add(New Button())
tabpage8 would be the name of the new created tabpage but like vb already told me, i cant add objects to a tabpage which doesnt exist at that time.
is there any way i can do that or have you any other ideas which could help me?

Your code is close. Try the following:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TabControl2.TabPages.Add("Test")
Dim tp = TabControl2.TabPages(TabControl2.TabPages.Count - 1)
Dim b = New Button()
b.Text = "My Button"
tp.Controls.Add(b)
AddHandler b.Click, AddressOf MyButton_Click
End Sub
Private Sub MyButton_Click(sender As Object, e As EventArgs)
MessageBox.Show("MyButton clicked")
End Sub
This code grabs the last page added and adds a button to it. It also configures the button as needed and adds an event handler.

Related

Add click events to ToolStripTextBox in VB.NET when created in code

I am creating tabs to keep track of open files. When I create them I can set their properties and add them to the list in a MenuStrip.
Before I do so I want to add a click event function. Since this is in a function and will be run multiple times, I need to have a dynamic way to do add these event handlers. I cannot write this:
Private Sub ToolStripTextBox1_Click(sender As Object, e As EventArgs) Handles ToolStripTextBox1.Click
' ...
End Sub
If I do this I can only name them all one name. I want to be able to add a click event that applies to them separately as individual items.
UPDATE:
Dim textFile As ToolStripTextBox = New ToolStripTextBox("textFile")
FileList.Items.Add(textFile)
textFile.Text = filename
textFile.ReadOnly = True
textFile.BackColor = Color.FromArgb(61, 61, 61)
textFile.ForeColor = Color.White
This is the creation and personalization code. Though when you guys suggested AddButton_Click() Handles AddButton.Click It doesn't work because AddButton isn't an actual button
You can keep track of the items, add add and remove click handlers with the following code
Private FileList As New List(Of ToolStripItem)()
' put this code where you add an item
Dim filename = "whatever"
Dim textFile As ToolStripTextBox = New ToolStripTextBox(filename)
textFile.Text = filename
textFile.ReadOnly = True
textFile.BackColor = Color.FromArgb(61, 61, 61)
textFile.ForeColor = Color.White
add(textFile)
Private Sub clickHandler(sender As Object, e As EventArgs)
Dim item = DirectCast(sender, ToolStripItem)
MessageBox.Show(item.Text)
End Sub
Private Sub add(textFile As ToolStripItem)
FileList.Add(textFile) ' Since I don't know what FileList is, I ued List
AddHandler textFile.Click, AddressOf clickHandler
OpenProjectToolStripMenuItem.DropDownItems.Add(textFile) ' add to whatever menu item you normally do
End Sub
Private Sub remove(textFile As ToolStripItem)
FileList.Remove(textFile)
RemoveHandler textFile.Click, AddressOf clickHandler
OpenProjectToolStripMenuItem.DropDownItems.Remove(textFile)
End Sub
The sample click event in your code includes this:
sender As Object
You can re-use this one event handler, because whichever menu item is clicked will be the sender. So you do something like this:
Private Sub ToolStripTextBox1_Click(sender As Object, e As EventArgs) Handles ToolStripTextBox1.Click
Dim menuItem = DirectCast(sender, ToolStripMenuItem)
If menuItem Is Nothing Then Return
'If you need to choose different code for each item:
Select Case menuItem.name
Case "some item"
Case "some other item"
End Select
End Sub
And you can connect your dynamic toolstrip items to this method using AddHandler:
AddHandler myMenuStrip.Click, AddressOf ToolSTripTextBox1_Click

Is there a way to put already created buttons into an array?

What I'm trying to do is put buttons I have already created into an array, however, whenever I look into the array it says that there is nothing in there? I was wondering if I'm doing something wrong.
Dim buttons As System.Windows.Forms.Button() = {Button1, Button2, Button3, Button4, Button5, Button6, Button7, Button8, Button9, Button10, Button11, Button12, Button13, Button14, Button15, Button16, Button17, Button18, Button19, Button20, Button21, Button22, Button23, Button24, Button25, Button26, Button27, Button28, Button29, Button30, Button31, Button32, Button33, Button34, Button35, Button36, Button37, Button38, Button39, Button40}
Private Sub ClearBtn_Click(sender As Object, e As EventArgs) Handles ClearBtn.Click
For i = 1 To 40
buttons(i).BackgroundImage = System.Drawing.Image.FromFile("leaf.png")
Next
End Sub
When the Clearbtn is clicked I get System.NullReferenceException: 'Object reference not set to an instance of an object.' And the array is empty. I've set the array to a global variable so it should work?
The problem is that the code that creates your array is executed before the form constructor, so before all the child controls are created. Of course those fields are Nothing at that point. The solution is to declare the field where you are but to create the array and assign it to that field in the Load event handler.
I would store the background image at form level, and build the list in the Load() event like this:
Dim buttons As New List(Of Button)
Dim imgClear As Image = System.Drawing.Image.FromFile("leaf.png")
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For i As Integer = 1 To 40
Dim ctl As Control = Me.Controls.Find("Button" & i, True).FirstOrDefault
If Not IsNothing(ctl) AndAlso TypeOf ctl Is Button Then
buttons.Add(DirectCast(ctl, Button))
End If
Next
End Sub
Private Sub ClearBtn_Click(sender As Object, e As EventArgs) Handles ClearBtn.Click
For Each btn As Button In buttons
btn.BackgroundImage = imgClear
Next
End Sub
Note that searching for the buttons in this manner will find them no matter where they are. They don't have to be directly contained by the form, or even in the same containers.

Index Selection in ListView created at runtime in Visual Basic (Visual Studio 2019)

I am trying to use a ListView box created at runtime and I am able to populate items but the SelectedIndexChanged event is not working. I know I am missing something really simple. Below is a minimal working example where I am creating the ListView on a button click and populating with a couple of items. When I select an item nothing happens in the SelectedIndexChanged event.
Public Class Form1
Dim lstMylist As ListView
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
lstMylist = New ListView()
lstMylist.Location = New Point(37, 312)
lstMylist.Size = New Size(150, 150)
Me.Controls.Add(lstMylist)
lstMylist.View = View.SmallIcon
Dim myListItem1 As ListViewItem
myListItem1 = lstMylist.Items.Add("Item 1")
Dim myListItem2 As ListViewItem
myListItem2 = lstMylist.Items.Add("Item 2")
End Sub
Private Sub lstMylist_SelectedIndexChanged(sender As Object, e As EventArgs)
MessageBox.Show("I am here")
Select Case lstMylist.FocusedItem.Index
Case 0
MessageBox.Show("item 1")
Case 1
MessageBox.Show("item 2")
Case Else
MessageBox.Show("invalid")
End Select
End Sub
End Class
You need to add the event handler to the ListView SelectedIndexChanged event
lstMylist = New ListView()
lstMylist.Location = New Point(37, 312)
lstMylist.Size = New Size(150, 150)
' Add the event handler for the listview
AddHandler lstMyList.SelectedIndexChanged, AddressOf lstMylist_SelectedIndexChanged
Me.Controls.Add(lstMylist)
lstMylist.View = View.SmallIcon
As outlined by djv it is important to call RemoveHandler if you remove the ListView
RemoveHandler lstMyList.SelectedIndexChanged, AddressOf lstMylist_SelectedIndexChanged
Steve's answer will work. But an alternative is to simply make your ListView WithEvents
Dim WithEvents lstMylist As ListView
and add Handles to the method declaration
Private Sub lstMylist_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstMylist.SelectedIndexChanged
This is more a VB.NET way of doing things. AddHandler is similar to C# Event += new EventHandler syntax.
Note, if using AddHandler, a matching RemoveHandler should appear if the ListView is to be removed and added repeatedly.

Button Array - how to pass a parameter to shared handler

I have a bit of code where i have a dynamically created array or buttons with staff pictures on them, as well as the staff's name. I've added one handler to handle any button click from any of the buttons. where i am stuck is, if you look at the code below, it all works fine, and if you click any of the buttons you get the "aha" test message. but i want the name of the staff clicked on (so btnArray(i).Text) to be passed to the handler for further processing. I tried adding a ByVal parameter to the handler but that caused an error. what's the correct way to do this? As i said, the code below works for me, i just am at a loss as to how to add the extra functionality.
Dim btnArray(staffcount) As System.Windows.Forms.Button
For i As Integer = 1 To staffcount - 1
btnArray(i) = New System.Windows.Forms.Button
btnArray(i).Visible = True
btnArray(i).Width = 80
btnArray(i).Height = 101
btnArray(i).BackgroundImage = Image.FromFile(picloc(i))
btnArray(i).BackgroundImageLayout = ImageLayout.Stretch
btnArray(i).Text = staffname(i)
Dim who As String
who = btnArray(i).Text
AddHandler btnArray(i).Click, AddressOf Me.theButton_Click
btnArray(i).ForeColor = Color.White
btnArray(i).TextAlign = ContentAlignment.BottomCenter
Dim fnt As Font
fnt = btnArray(i).Font
btnArray(i).Font = New Font(fnt.Name, 10, FontStyle.Bold)
FlowLayoutPanel1.Controls.Add(btnArray(i))
Next i
End Sub
Private Sub theButton_Click()
MsgBox("aha")
End Sub
First, correct the signature of your shared handler.
Private Sub theButton_Click(sender As Object, e As EventArgs)
End Sub
Once that is done getting the text of the button clicked is a simple matter.
Private Sub theButton_Click(sender As Object, e As EventArgs)
Dim textOfButtonClicked As String = DirectCast(sender, Button).Text
MessageBox.Show(textOfButtonClicked)
End Sub
The sender is the button that was clicked. Since signatures use objects for the sender the DirectCast 'changes' it to button and you then can access the .Text property of the button.
If there are more manipulations you want to perform on the clicked button you could do it this way
Private Sub theButton_Click(sender As Object, e As EventArgs)
Dim whBtn As Button = DirectCast(sender, Button) ' get reference to button clicked
Dim textOfButtonClicked As String = whBtn.Text
MessageBox.Show(textOfButtonClicked)
'e.g. change the color
whBtn.BackColor = Color.LightYellow
End Sub

Raising events from a List(Of T) in VB.NET

I've ported a large VB6 to VB.NET project and while it will compile correctly, I've had to comment out most of the event handlers as to get around there being no array collection for winform objects and so putting the various objects that were in at the collection array into a List object.
For example, in VB6 you could have an array of Buttons. In my code I've got
Dim WithEvents cmdButtons As New List(Of Button)
(and in the Load event, the List is propagated)
Obviously, you can't fire an event on a container. Is there though a way to fire the events from the contents of the container (which will have different names)?
In the Button creation code, the event name is there, but from what I understand the handler won't intercept as the Handles part of the code is not there (commented out).
I'm not exactly sure what you're after, but if you want to be able to add event handlers to some buttons in a container and also have those buttons referenced in a List, you can do something like
Public Class Form1
Dim myButtons As List(Of Button)
Private Sub AddButtonsToList(targetContainer As Control)
myButtons = New List(Of Button)
For Each c In targetContainer.Controls
If TypeOf c Is Button Then
Dim bn = DirectCast(c, Button)
AddHandler bn.Click, AddressOf SomeButton_Click
myButtons.Add(bn)
End If
Next
End Sub
Private Sub SomeButton_Click(sender As Object, e As EventArgs)
Dim bn = DirectCast(sender, Button)
MsgBox("You clicked " & bn.Name)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' GroupBox1 has some Buttons in it
AddButtonsToList(GroupBox1)
End Sub
End Class