VB.net
Windows Forms
I need to get the selected item in a ComboBox dynamically. I need to do this dynamically because I will make hundreds of ComboBox, and all of them need to have their own separate control.
Right now, with the following code, I am able to generate 3 different controls (including a ComboBox), and then dynamically delete each control. This works great, but I can't figure out how to get or set information from these controls.
Copy and paste the following code in a windows form, and add a FlowLayoutPanel called "pnlLayout", and a button called BtnAdd
Notice the "'get the selected item in a ComboBox" at the bottom of the code
Public Class Form1
ReadOnly deleteButtons As List(Of Button)
ReadOnly textBoxes As List(Of TextBox)
ReadOnly comboBoxes As List(Of ComboBox)
Sub New()
' This call is required by the designer
InitializeComponent()
' Add any initialization after the InitializeComponent() call
deleteButtons = New List(Of Button)
textBoxes = New List(Of TextBox)
comboBoxes = New List(Of ComboBox)
End Sub
Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles BtnAdd.Click
Dim elementCount As Integer = deleteButtons.Count
Dim btn As New Button With {
.Width = 100,
.Height = 20,
.Text = "Delete " & elementCount.ToString
}
AddHandler btn.Click, AddressOf BtnDelete
deleteButtons.Add(btn)
Dim txt As New TextBox With {
.Width = 100,
.Height = 20
}
textBoxes.Add(txt)
Dim cmb As New ComboBox With {
.Width = 100,
.Height = 20
}
AddHandler btn.Click, AddressOf BtnDelete
AddHandler cmb.SelectedIndexChanged, AddressOf cmbChanged
comboBoxes.Add(cmb)
pnlLayout.Controls.Add(btn)
pnlLayout.Controls.Add(txt)
pnlLayout.Controls.Add(cmb)
End Sub
Private Sub BtnDelete(sender As Object, e As EventArgs)
Dim senderButton As Button = DirectCast(sender, Button)
Dim txt As TextBox = textBoxes(deleteButtons.IndexOf(senderButton))
Dim cmb As ComboBox = comboBoxes(deleteButtons.IndexOf(senderButton))
pnlLayout.Controls.Remove(senderButton)
pnlLayout.Controls.Remove(txt)
pnlLayout.Controls.Remove(cmb)
End Sub
Private Sub cmbChanged(sender As Object, e As EventArgs)
'get the selected item in a ComboBox
End Sub
End Class
What I have tried:
I tried playing with the btnDelete and tried using it to get information but it did not work for me
I am also new to coding (I am 17 years old)