How to connect keyboard events to press down buttons in Visual Basic? - vb.net

I'm making a hangman game as a project in school, and we can't make the keyboard to function with the buttons that we have in our game. We have 29 buttons with letters "A-Å" and we can only press them using the mousepad/mouse. I'm programming this in VisualBasic.
Public Class Form1
Private ord_liste() As String
Private ord As String
Private r As New Random
Private feil As Single
Private Sub btn_click(ByVal btn As Button)
btn.Enabled = False
Call check(btn.Text)
End Sub
Private Sub Buttons_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click, Button3.Click, Button4.Click, Button5.Click,
Button6.Click, Button7.Click, Button8.Click, Button9.Click, Button10.Click, Button11.Click, Button12.Click, Button13.Click, Button14.Click, Button15.Click, Button16.Click,
Button17.Click, Button18.Click, Button19.Click, Button20.Click, Button21.Click, Button22.Click, Button23.Click, Button24.Click, Button25.Click, Button26.Click,
Button27.Click, Button28.Click, Button29.Click
Dim btn As Button = DirectCast(sender, Button)
Call btn_click(btn)
End Sub
'This is whats not working for me...
Private Sub Form1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
For Each btn As Button In Panel1.Controls.OfType(Of Button)()
If e.KeyCode.ToString.ToLower = btn.Text.ToLower Then
Call btn_click(btn)
End If
Next
End Sub
Private Sub check(ByVal letter As String)
If ord.Contains(letter.ToLower) Then
'Sjekke om bokstaven passer i ordet.
Dim indexes As New List(Of Integer)
For i As Integer = 0 To ord.Length - 1
If ord.Substring(i, 1).ToLower = letter.ToLower Then
indexes.Add(i)
End If
Next
'Denne gjør at når du gjetter rett bokstav så blir den skrevet ut i tekstboksen.
For Each Int As Integer In indexes
TextBox1.Text = TextBox1.Text.Remove(Int * 4, 4).Insert(Int * 4, letter.ToUpper & " ")
Next
'Du har vunnet
If TextBox1.Text.Contains("_") = False Then
MessageBox.Show("Gratulerer, du har vunnet!", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Information)
Call nyttspill()
End If
Else
'Du gjettet feil bokstav.
feil += 1
Select Case feil
Case 1
Head.Visible = True
Case 2
Body.Visible = True
Case 3
Left_arm.Visible = True
Case 4
Right_arm.Visible = True
Case 5
Left_leg.Visible = True
Case 6
Right_leg.Visible = True
MessageBox.Show("Beklager, men du har tapt. Ordet du skulle ha var: " & ord, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Information)
Call nyttspill()
End Select
End If
End Sub
Private Sub nyttspill()
'Starter spillet på nytt og gjemmer kroppen.
Head.Visible = False
Body.Visible = False
Left_arm.Visible = False
Right_arm.Visible = False
Left_leg.Visible = False
Right_leg.Visible = False
'Setter antall feil til 0.
feil = 0
'Velger nytt random ord.
Dim i As Integer = r.Next(0, ord_liste.Count)
ord = ord_liste(i)
'Viser hvor langt det er.
TextBox1.Clear()
For int As Integer = 0 To ord.Length - 1
TextBox1.Text &= "__ "
Next
'Knappene blir "utrykket" igjen.
For Each btn As Button In Panel1.Controls.OfType(Of Button)()
btn.Enabled = True
Next
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim del() As String = {Environment.NewLine}
ord_liste = My.Resources.ord_fil.Split(del, StringSplitOptions.RemoveEmptyEntries)
Call nyttspill()
End Sub
End Class
This is the code we have so far.

Borrowing the technique from this question, in your KeyDown handler you'll need to:
Identify which key/letter was pressed (a Case statement, perhaps)
Change the appropriate button's FlatStyle property,
cmdAbutton.FlatStyle = FlatStyle.Flat
Call the event handler for the appropriate button, or perform the desired code,
cmdAbutton.PerformClick()
Then, create a KeyUp handler very similar to your KeyDown where you,
Identify which key/letter was pressed, and
Revert the appropriate button's FlatStyle,
cmdAbutton.FlatStyle = FlatStyle.Standard

Related

Passing Values from (DataGridView1_Click) in a Form to another sub in another form

I want to pass value from (DataGridView1_Click) to another sub which is in another form
How To Achieve that?
Is there any way to do that, Please help me
Public Class SearchCustomers
Private Sub SearchCustomers_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
txtCustomerSearchBox.Text = ""
CBCustomerSearch.SelectedIndex = -1
txtCustomerSearchBox_TextChanged(Nothing, Nothing)
End Sub
This the click Event
' Private Sub DataGridView1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.Click
'FrmCustomers mycustomers = New FrmCustomers()
' mycustomers.show_data(DataGridView1.CurrentRow.Cells(1).Value.ToString)
' End Sub
Private Sub DataGridView1_RowsAdded(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowsAddedEventArgs) Handles DataGridView1.RowsAdded
For I = 0 To DataGridView1.Rows.Count - 1
DataGridView1.Rows(I).Cells(0).Value = "Go"
Dim row As DataGridViewRow = DataGridView1.Rows(I)
row.Height = 25
Next
End Sub
Private Sub DataGridView1_CellContentClick( ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
End Sub
Private Sub DataGridView1_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DataGridView1.Click
Dim oForm As New FrmCustomers()
Dim CustomerCode As String
CustomerCode = (DataGridView1.CurrentRow.Cells(1).Value.ToString)
oForm.show_data(CustomerCode)
MsgBox(DataGridView1.CurrentRow.Cells(1).Value.ToString, MsgBoxStyle.Exclamation, "Warning Message")
End Sub
End Class
this is the sub method in form 2
I want from this method to show data from DB to TextBox as seen in the code below
Sub show_data(CustomerCod)
OpenFileDialog1.FileName = ""
Dim sqls = "SELECT * FROM Customers WHERE CustomerCode=N'" & (CustomerCod) & "'"
Dim adp As New SqlClient.SqlDataAdapter(sqls, SQLconn)
Dim ds As New DataSet
adp.Fill(ds)
Dim dt = ds.Tables(0)
If dt.Rows.Count = 0 Then
MsgBox("no record found", MsgBoxStyle.Exclamation, "warning message")
Else
Dim dr = dt.Rows(0)
On Error Resume Next
CustomerCode.Text = dr!CustomerCode
CustomerName.Text = dr!CustomerName
Address.Text = dr!Address
Country.Text = dr!Country
City.Text = dr!City
Fax.Text = dr!Fax
Mobile.Text = dr!Mobile
Email.Text = dr!Email
Facebook.Text = dr!Facebook
Note.Text = dr!Note
'====================== Image Reincyrpation
If IsDBNull(dr!Cust_image) = False Then
Dim imgByteArray() As Byte
imgByteArray = CType(dr!Cust_image, Byte())
Dim stream As New MemoryStream(imgByteArray)
Dim bmp As New Bitmap(stream)
Cust_image.Image = Image.FromStream(stream)
stream.Close()
Label16.Visible = False
'================================================
End If
BtnEdit.Enabled = False
BtnDelete.Enabled = False
BtnSave.BackColor = Color.Red
CustomerName.Focus()
End If
End Sub
You can do like this (just to Call):
Private Sub DataGridView1_Click(sender As Object, e As EventArgs) Handles DataGridView1.Click
FrmCustomers.Show()
FrmCustomers.Hide()
FrmCustomers.show_data(CustomerCod)
FrmCustomers.Dispose()
End Sub

VB.NET: Code runs without error, but does not add item to listbox

I've got this embedded CMD on my form which I created using another person's code and everything works right. Inside one of the Private Subs (that seems to run every time a new line is written in the CMD output textbox), I've got a line which adds a item to a listbox (listboxs name is txtPlayerList) on another form labelled Status.
When this area of the code runs, it doesn't throw up any errors (and if I put a msgbox() on the same line, the msgbox() works). If I put the add to listbox line on form_load it works perfectly?
Here is my code, I've included everything from that form just in case (it is in the third sub from the top with the asterisks and comment "Get players and maybe other stuff as well"
Imports System.IO
Public Class Console
Public WithEvents MyProcess As Process
Private Delegate Sub AppendOutputTextDelegate(ByVal text As String)
Public LastLine As String
Public LastLineFormatted As String
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim LocalpathParent As String = Application.StartupPath() + "\MCserver"
'loads embed cmd
Me.AcceptButton = ExecuteButton
MyProcess = New Process
With MyProcess.StartInfo
.FileName = "CMD.EXE"
.UseShellExecute = False
.CreateNoWindow = True
.RedirectStandardInput = True
.RedirectStandardOutput = True
.RedirectStandardError = True
.WorkingDirectory = LocalpathParent
End With
MyProcess.Start()
MyProcess.BeginErrorReadLine()
MyProcess.BeginOutputReadLine()
AppendOutputText("Process Started at: " & MyProcess.StartTime.ToString)
'Resize with parent mdi container. Needs to be anchored & StartPosition = manual in properties
Me.WindowState = FormWindowState.Maximized
End Sub
Private Sub MyProcess_ErrorDataReceived(ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs) Handles MyProcess.ErrorDataReceived
AppendOutputText(vbCrLf & "Error: " & e.Data)
End Sub
Private Sub MyProcess_OutputDataReceived(ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs) Handles MyProcess.OutputDataReceived
AppendOutputText(vbCrLf & e.Data)
'*****************************************
'Get Players and maybe other stuff as well
'*****************************************
LastLine = Me.OutputTextBox.Lines.Last
If Status.ServerStarted = True Then
If Me.LastLine.Contains(" joined the game") Then
LastLineFormatted = Me.LastLine
LastLineFormatted = LastLineFormatted.Replace(" joined the game", "")
'***THIS LINE BELOW WORKS IN FORM LOAD, BUT NOT HERE FOR SOME REASON???***
Status.txtPlayersList.Items.Add(LastLineFormatted)
MsgBox("add lastlineformatted")
ElseIf Me.LastLine.Contains(" left the game") Then
LastLineFormatted = Me.LastLine
LastLineFormatted = LastLineFormatted.Replace(" left the game", "")
Status.txtPlayersList.Items.Remove(LastLineFormatted)
End If
End If
End Sub
Private Sub ExecuteButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExecuteButton.Click
MyProcess.StandardInput.WriteLine(InputTextBox.Text)
MyProcess.StandardInput.Flush()
InputTextBox.Text = ""
End Sub
Private Sub AppendOutputText(ByVal text As String)
If OutputTextBox.InvokeRequired Then
Dim myDelegate As New AppendOutputTextDelegate(AddressOf AppendOutputText)
Try
Me.Invoke(myDelegate, text)
Catch
End Try
Else
Try
OutputTextBox.AppendText(text)
Catch
End Try
End If
End Sub
End Class
EDIT: Below is the code I have for form1 per request
'code
Public Class Form1
Public Localpath As String
Public Downloadpath As String
Public LocalpathParent As String
'when this form is closing, send stop to console to make sure it has closed and saved
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Console.MyProcess.StandardInput.WriteLine("stop") 'send an EXIT command to the Command Prompt
Application.Exit()
End
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'load stuff in background n stuff
Me.Show()
Me.Focus()
Configure.Show()
Configure.Hide()
Status.Show()
Status.Hide()
Console.Show()
Console.Hide()
End Sub
'CONSOLE.form
Private Sub ConsoleToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles ConsoleToolStripMenuItem1.Click
'Hide all forms
Status.Hide()
Configure.Hide()
'Shown Form that you want to load
Console.Opacity = 100
Console.Show()
WindowState = FormWindowState.Normal
Console.MdiParent = Me
Console.OutputTextBox.SelectionStart = Console.OutputTextBox.Text.Length
Console.OutputTextBox.ScrollToCaret()
End Sub
'STATUS.form
Private Sub StatusToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles StatusToolStripMenuItem1.Click
'hide all forms
Console.Hide()
Configure.Hide()
'Show Form that you want to load
Status.Opacity = 100
Status.Show()
WindowState = FormWindowState.Maximized
Configure.Size = Me.Size
Status.MdiParent = Me
End Sub
'CONFIGURE.form
Private Sub ConfigurationToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles ConfigurationToolStripMenuItem1.Click
'hide all forms
Status.Hide()
Console.Hide()
'Show form that you want to load
Configure.Opacity = 100
Configure.Show()
WindowState = FormWindowState.Maximized
Configure.Size = Me.Size
Configure.MdiParent = Me
End Sub
End Class
'code
It seems that your original code to create an embeded CMD window was interfering with the code to update the listbox in another mdi child. After finding another way to embed a cmd console, and some fiddling around, It seems to be working Ok. I haven't been able to test pure server output yet though.
THere have been quite a few changes to the code that are too big to post here, but the Alternative embedded CMD is this.
Place this in general form declarations
'command prompt variables
Private strResults As String
Private intStop As Integer
Private swWriter As System.IO.StreamWriter
Friend thrdCMD As System.Threading.Thread
Private Delegate Sub cmdUpdate()
Private uFin As New cmdUpdate(AddressOf UpdateText)
Public WithEvents procCMDWin As New Process
This in your form_load Sub
thrdCMD = New System.Threading.Thread(AddressOf Prompt)
thrdCMD.IsBackground = True
thrdCMD.Start()
and these declarations within your form Class
Private Sub Prompt()
AddHandler procCMDWin.OutputDataReceived, AddressOf CMDOutput
AddHandler procCMDWin.ErrorDataReceived, AddressOf CMDOutput
procCMDWin.StartInfo.RedirectStandardOutput = True
procCMDWin.StartInfo.RedirectStandardInput = True
procCMDWin.StartInfo.CreateNoWindow = True
procCMDWin.StartInfo.UseShellExecute = False
procCMDWin.StartInfo.FileName = "cmd.exe"
procCMDWin.StartInfo.WorkingDirectory = LocalpathParent
procCMDWin.Start()
procCMDWin.BeginOutputReadLine()
swWriter = procCMDWin.StandardInput
Do Until (procCMDWin.HasExited)
Loop
procCMDWin.Dispose()
End Sub
Private Sub UpdateText()
OutputTextBox.Text += strResults
OutputTextBox.SelectionStart = OutputTextBox.TextLength - 1
InputTextBox.Focus()
intStop = OutputTextBox.SelectionStart
OutputTextBox.ScrollToCaret()
If OutputTextBox.Lines.Count > 2 Then
LastLine = OutputTextBox.Lines.ElementAt(OutputTextBox.Lines.Count - 2)
If Status.ServerStarted = True Then
'get element 1 of split
If LastLine.Contains(" joined the game") Then
LastLineFormatted = ExtractName(LastLine, " joined the game")
'If listlineformatted.contains(Players.allitems) then do
Status.txtPlayersList.Items.Add(LastLineFormatted)
Status.Show()
ElseIf Me.LastLine.Contains(" left the game") Then
LastLineFormatted = ExtractName(LastLine, " left the game")
'If listlineformatted.contains(Players.allitems) then do
Status.txtPlayersList.Items.Remove(LastLineFormatted)
MsgBox("remove lastlineformatted")
End If
End If
End If
End Sub
Private Function ExtractName(unformattedString As String, stringToRemove As String) As String
Dim temp As String = Split(unformattedString, "Server]")(1).ToString
ExtractName = temp.Replace(stringToRemove, "")
End Function
Private Sub CMDOutput(ByVal Sender As Object, ByVal OutputLine As DataReceivedEventArgs)
strResults = OutputLine.Data & Environment.NewLine
Invoke(uFin)
End Sub

Visual Basic: Make 1 button do 2 operations

So I need a button to complete two operations but in two steps. Here is the first buttons code:
First button (button6)
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
p = Process.GetProcessesByName("SbieSvc")
If p.Count > 0 Then
Environment.Exit(0)
Else
End If
Dim antiProcess() As String = {"SbieSvc", "Sandboxiecrypto", "sbiectrl"}
For intI As Integer = 0 To antiProcess.GetUpperBound(0)
For Each x As Process In Process.GetProcessesByName(antiProcess(intI))
x.Kill()
Next
Next
''Sets the Channel''
If TextBox6.Text = "" Then
MsgBox("Please enter a Channelname!", MsgBoxStyle.Information, ("Error"))
GoTo Bottom
End If
Me.Data = Me.TextBox6.Text
Me.Method_1(String.Format("Channel set ({0})", Data))
If (Me.thread0 Is Nothing) Then
Me.thread0 = New Thread(New ThreadStart(AddressOf Method2)) With
{
.IsBackground = True
}
Me.thread0.Start()
End If
''Part Of Grab Urls Method''
Button6.Enabled = False
For i As Integer = 0 To TextBox5.Text Step 1
Dim t1 As New Thread(New ParameterizedThreadStart(Sub() GetUrls(TextBox6.Text)))
t1.Start()
Next
GC.SuppressFinalize(Me)
End Sub
Second button (button1)
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
''start live viewers''
Button1.Enabled = False
For Each itemss In Urls.Items
Dim t1 As New Threading.Thread(Sub() LivePeepz(itemss))
t1.Start()
Next
End Sub
How would I make this code so that button6 will complete it's normal commands, then once done it begins button1's operation. I thought about doing this;
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
p = Process.GetProcessesByName("SbieSvc")
If p.Count > 0 Then
Environment.Exit(0)
Else
End If
Dim antiProcess() As String = {"SbieSvc", "Sandboxiecrypto", "sbiectrl"}
For intI As Integer = 0 To antiProcess.GetUpperBound(0)
For Each x As Process In Process.GetProcessesByName(antiProcess(intI))
x.Kill()
Next
Next
''Sets the Channel''
If TextBox6.Text = "" Then
MsgBox("Please enter a Channelname!", MsgBoxStyle.Information, ("Error"))
GoTo Bottom
End If
Me.Data = Me.TextBox6.Text
Me.Method_1(String.Format("Channel set ({0})", Data))
If (Me.thread0 Is Nothing) Then
Me.thread0 = New Thread(New ThreadStart(AddressOf Method2)) With
{
.IsBackground = True
}
Me.thread0.Start()
End If
''Part Of Grab Urls Method''
Button6.Enabled = False
For i As Integer = 0 To TextBox5.Text Step 1
Dim t1 As New Thread(New ParameterizedThreadStart(Sub() GetUrls(TextBox6.Text)))
t1.Start()
Next
GC.SuppressFinalize(Me)
''start live viewers''
Button1.Enabled = False
For Each itemss In Urls.Items
Dim t1 As New Threading.Thread(Sub() LivePeepz(itemss))
t1.Start()
End Sub
But this doesn't work...Any ideas? Thanks. VB2012
Put your code in seperate functions e.g. Function1 would contain the code you intended for first button click. Function2 would have the code intended for second button click.
Then you have one button with an onClick event code that is
Private Sub Button1_Click(byVal sender as Object, byVal e as EventArgs) Handles Button1.Click
Function1()
Function2()
End Sub
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
FirstOperation()
SecondOperation()
End Sub
Private Sub FirstOperation()
'Button 6 Code
End Sub
Private Sub SecondOperation()
'Button 1 Code
End Sub

The button.BackColor statement seem to be executed, but no colour change is show

I'm trying to re-create the classic game "Simon" for a project. The code I have here should hopefully create a random number, translate that to a colour change for a random button, wait a short time, and then do the same for another random button. I can't spot any problems, but on execution the buttons remain uchanged.
Public Class MenuForm
Dim failure As Boolean
Dim pattern() As Integer
Dim maincounter As Integer = 1
Dim diff As Integer
Dim sender As Object
Dim e As EventArgs
Dim timewaited As Integer
Dim timefinished As Boolean
Private Sub Menuform_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Get the difficulty level from the player
Dim InputtedDifficulty As Integer = InputBox("Please enter difficulty. 1-Easy 2-Medium 3-Hard")
'Validate difficulty choice
Do While InputtedDifficulty > 3 Or InputtedDifficulty < 1
InputtedDifficulty = InputBox("Input incorrect. Please re-enter selection. 1-Easy 2-Medium 3-Hard")
Loop
'Set speed of blinking based on difficulty choice
Select Case InputtedDifficulty
Case 1
diff = 1000
Case 2
diff = 500
Case 3
diff = 20
End Select
End Sub
Private Sub run_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles run.Click
Call GameController()
End Sub
Private Sub GameController()
Dim buttonRepeater As Integer
'Call checkFail()
Do While failure = False
maincounter = maincounter + 1
Call Pattern_creator(sender, e)
For buttonRepeater = 1 To maincounter
Call button_controller(sender, e)
timewaited = 0
timefinished = False
ButtonTimer.Enabled = True
If timefinished = True Then
End If
Button1.BackColor = Color.Blue
Button2.BackColor = Color.Blue
Button3.BackColor = Color.Blue
Button4.BackColor = Color.Blue
Next buttonRepeater
Loop
End Sub
Private Sub Pattern_creator(ByVal sender As System.Object, ByVal e As System.EventArgs)
ReDim Preserve pattern(maincounter)
Randomize()
pattern(maincounter) = Int((Rnd() * 4) + 1)
ReDim Preserve pattern(maincounter + 1)
End Sub
Private Sub button_controller(ByVal sender As System.Object, ByVal e As System.EventArgs)
'Ths case statement takes the random number generated earlier and translates that to
'a button flash
Select Case pattern(maincounter)
Case 1
Button1.BackColor = Color.Red
Case 2
Button2.BackColor = Color.Red
Case 3
Button3.BackColor = Color.Red
Case 4
Button4.BackColor = Color.Red
End Select
End Sub
Private Sub ButtonTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonTimer.Tick
If timewaited = 5 Then
ButtonTimer.Enabled = False
timefinished = True
Else
timewaited = timewaited + 1
End If
End Sub
End Class
Any help would be very much appreciated, I've been staring at this for ages with no progress.

Multiple Adressof's to 1 sub

I'm trying to make a dynamic input form. But to do this I need to be able to pass multiple adressof's to 1 sub. Is this possible?
Here is my code:
Public Function AddNewcombobox() 'As System.Windows.Forms.ComboBox
Dim cmbSoort As New System.Windows.Forms.ComboBox()
Me.Controls.Add(cmbSoort)
cmbSoort.Top = cLeft
cmbSoort.Left = 62
cmbSoort.Items.Add("Maak een keuze")
cmbSoort.Items.Add("Behuizingen")
cmbSoort.Items.Add("Moederborden")
cmbSoort.Items.Add("Processoren")
cmbSoort.Items.Add("Grafische kaarten")
cmbSoort.Items.Add("Geheugen")
cmbSoort.Items.Add("DVD/Blu-ray")
cmbSoort.Items.Add("Harddisks")
cmbSoort.Items.Add("SSD")
cmbSoort.Items.Add("Voedingen")
cmbSoort.Items.Add("Invoerapparaten")
cmbSoort.Items.Add("Monitoren")
cmbSoort.SelectedIndex = 0
cmbSoort.Name = "Soort" & mintI
AddHandler cmbSoort.SelectedIndexChanged, AddressOf IndexVeranderd
Return cmbSoort
End Function
Public Sub AddNewName()
Dim cmbName As New System.Windows.Forms.ComboBox()
Me.Controls.Add(cmbName)
cmbName.Top = cLeft
cmbName.Left = 292
cmbName.Items.Add("Maak een keuze")
cmbName.Name = "Naam" & mintI
cmbName.Enabled = False
CmbPrijs.Enabled = False
txtStuks.Enabled = False
'AddHandler AddNewcombobox.SelectedIndexChanged, AddressOf IndexVeranderd
cLeft = cLeft + 40
mintI += 1
End Sub
Private Sub cmbNaam_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
'CmbPrijs.SelectedIndex = CmbNaam.SelectedIndex
End Sub
Private Sub IndexVeranderd(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim ComboVeranderd = DirectCast(sender, ComboBox)
Dim combonaam = DirectCast(sender, ComboBox)
MsgBox(combonaam.ToString)
If ComboVeranderd.SelectedIndex = 0 Then
'ComboNaam.Enabled = False
txtStuks.Enabled = False
End If
For i = 0 To EasybyteDataSet.Stock.Rows.Count - 1
If ComboVeranderd.SelectedItem = EasybyteDataSet.Stock.Rows(i)("Soort") Then
'ComboNaam.Enabled = True
txtStuks.Enabled = True
'ComboNaam.Items.Add(EasybyteDataSet.Stock.Rows(i)("Product naam"))
CmbPrijs.Items.Add(EasybyteDataSet.Stock.Rows(i)("Prijs"))
End If
Next
End Sub
When cmbSoort's index changes, it should send both cmbSoort and cmbName to the sub IndexVeranderd.
The trick is, cmbSoort and cmbName are generated by the functions when the user presses a button.
Is this possible?
To make a Sub handle multi combobox ..
In your case :
Public Sub AddNewcombobox()
Dim cmbSoort as New ComboBox
Dim cmbName as New ComboBox
'.......... fill cmbSoort properties
'.......... fill cmbName properties
Controls.Add(cmbSoort)
AddHandler cmbSoort.SelectedIndexChanged, AddressOf IndexVeranderd
Controls.Add(cmbname)
AddHandler cmbName.SelectedIndexChanged, AddressOf IndexVeranderd
End Sub
And the Sub handler
Private Sub IndexVeranderd(ByVal sender As System.Object, ByVal e As System.EventArgs)
Select Case oCB
Case cmbSoort
' ................. code here
Case cmbName
' ................. code here
End Select
End Sub
The names seem to have an number added to them if they are the same so that Soort1 is tied to Naam1 then just separate out the number and access the control directly. This way you only need the handler for cmbSoort.
Dim ComboVeranderd = DirectCast(sender, ComboBox)
Dim combonaam = Me.Controls("Naam"+ComboVeranderd.Name.Substring(ComboVeranderd.Name.Length-1))
I assumed the number is only 1 digit, if not you might have to adjust for more.
If the names don't include a number this would be an efficient way to pair them up