ComboBox array on select event vb.net - arrays

Here is my code to add a combobox array to a groupbox array
Dim gbQuoteProduct(5) As GroupBox
Dim cmboBoxQuoteProduct(5) As ComboBox
gbQuoteProduct(n) = New GroupBox
With gbQuoteProduct(n)
.Text = ""
.Location = New Point(10, 5 + n * 70)
.Width = 300
.Height = 70
End With
pnlQuoteProducts.Controls.Add(gbQuoteProduct(n))
cmboBoxQuoteProduct(n) = New ComboBox
With cmboBoxQuoteProduct(n)
.Items.Add("A")
.Items.Add("B")
.Items.Add("C")
.Items.Add("D")
.Text = ""
.Location = New Point(60, 15)
End With
gbQuoteProduct(n).Controls.Add(cmboBoxQuoteProduct(n))
This works fine but I want to add another combobox array to the groupbox array when something is selected from the existing combobox array.
When I try the following:
Private Sub cmboBoxQuoteProduct_SelectedIndexChanged(ByVal sender A
_ Object, ByVal e As System.EventArgs) Handles
_cmboBoxQuoteProduct().SelectedIndexChanged
End Sub
I get the error: "Expected "."" where I have the "()" after cmboBoxQuoteProduct
Any help is much appreciated.
Thanks in advance

Related

Why does my data does not display after changing tabs?

I'm using a DataGrid with TabControl. When I move to the 2nd tab my data is not displaying in the datagridview. My 2nd IF statement is not getting executed, I'm not sure why either. Only the 1st statement is being execute in selectedIndex 0. Please help me out.
Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl1.SelectedIndexChanged
If TabControl1.SelectedIndex = 0 Then
MyCn.Open()
MyDatAdp = New SqlDataAdapter("select * from Books", MyCn)
MyCmdBld = New SqlCommandBuilder(MyDatAdp)
MyDatAdp.Fill(MyDataTbl)
DataGridView1.DataSource = MyDataTbl
MyCn.Close()
If TabControl1.SelectedIndex = 1 Then
MyCn.Open()
MyDatAdp = New SqlDataAdapter("select * from Orders", MyCn)
MyCmdBld = New SqlCommandBuilder(MyDatAdp)
MyDatAdp.Fill(MyDt2)
DataGridView2.DataSource = MyDt2
MyCn.Close()
End If
End If
End Sub
Try to change the If TabControl1.SelectedIndex To If TabControl1.SelectedTab is yourTabPage Then
And see this Link for your reference.

VB.NET add or subtract an integer value to a SQL Server value into a label when selecting a combobox item

Following my previous question answered by #Andrew Morton, I have one more :)
Here is my whole code (not very long for now) :
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.Sql
Public Class Form1
Sub PopulateCB()
Dim connection As String = "Data Source=.\SQLEXPRESS;Initial Catalog=OST;Integrated Security=True"
Dim sql = "SELECT * FROM liste_unités"
Dim dt As New DataTable
Using conn As New SqlConnection(connection),
da As New SqlDataAdapter(sql, conn)
da.Fill(dt)
End Using
ComboBoxC1L1.DataSource = dt
ComboBoxC1L1.DisplayMember = "nom_unité"
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
PopulateCB()
End Sub
Private Sub ComboBoxC1L1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBoxC1L1.SelectedIndexChanged
Dim cb = DirectCast(sender, ComboBox)
If cb.SelectedIndex >= 0 Then
Dim val = DirectCast(cb.SelectedItem, DataRowView).Row.Field(Of Integer)("cout_unité")
If ComboBoxQC1L1.Text = "ordinaire" Then
LabelPointsC1L1.Text = val
ElseIf ComboBoxQC1L1.Text = "médiocre" Then
LabelPointsC1L1.Text = val - 2
ElseIf ComboBoxQC1L1.Text = "élite" Then
LabelPointsC1L1.Text = val + 2
End If
If cb.SelectedIndex >= 0 Then
Dim val2 = DirectCast(cb.SelectedItem, DataRowView).Row.Field(Of String)("type_unité")
LabelUnitType.Text = val2
End If
End If
Try
Dim totalC1L1 As Integer
totalC1L1 = CInt(TextBoxC1L1.Text) * CInt(LabelPointsC1L1.Text)
LabelTotalC1L1.Text = totalC1L1
Catch ex As Exception
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ComboBoxQC1L1.Text = "ordinaire"
End Sub
Private Sub TextBoxC1L1_TextChanged(sender As Object, e As EventArgs) Handles TextBoxC1L1.TextChanged
Try
Dim totalC1L1 As Integer
totalC1L1 = CInt(TextBoxC1L1.Text) * CInt(LabelPointsC1L1.Text)
LabelTotalC1L1.Text = totalC1L1
Catch ex As exception
End Try
End Sub
End Class
Here is the program interface
Here is the SQL table look
Here is the program interface when the Button has been clicked
Red Arrow ComboBox text is a DropDownStyle box with 3 possible text choices:
ordinaire,
élite,
médiocre
What I want to do: when changing the red arrow combobox text, the cout_unité label should change too with a "cout_unité -2" in case of "médiocre" ComboBox text, or "cout_unité +2" in case of "élite" ComboBox text or remain = to "cout_unité" if the selected text is "ordinaire".
And it should calculate this only once from the original "cout_unité" value in the table (in case of clicking 10 times on "ordinaire", it shouldn't subtract 10 * 2 to the "cout_unité" value, only 1 * 2)
I can do it in the ComboBoxC1L1 (see code) but I can't reproduce it with this red arrow combobox (probably because of the type of data into this combobox which are "strings", I don't know).
Many thanks :)
Since there is only a single Handles clause, the following line is unnecessary. The sender can only be the ComboBox in the Handles.
Dim cb = DirectCast(sender, ComboBox)
If you set the ValueMember of the combo in the PopulateCB method, you can save a long line of code making the code more readable.
Dim val = DirectCast(cb.SelectedItem, DataRowView).Row.Field(Of Integer)("cout_unité")
To:
Dim val = CInt(ComboBoxC1L1.SelectedValue)
We need the CInt since SelectedValue is an Object.
Don't assign the DataSource until after the DisplayMember and ValueMember are set.
You are checking twice for ComboBoxC1L1.SelectedIndex >= 0.
Just include the unit type in the first If.
The user may not have to trigger the SelectedIndexChanged event if the correct value is already selected. Maybe a button click would be better.
Sub PopulateCB()
Dim connection As String = "Data Source=.\SQLEXPRESS;Initial Catalog=OST;Integrated Security=True"
Dim sql = "SELECT * FROM liste_unités"
Dim dt As New DataTable
Using conn As New SqlConnection(connection),
da As New SqlDataAdapter(sql, conn)
da.Fill(dt)
End Using
ComboBoxC1L1.DisplayMember = "nom_unité"
ComboBoxC1L1.ValueMember = "cout_unité"
ComboBoxC1L1.DataSource = dt
End Sub
Private Sub btnCalculateValue_Click(sender As Object, e As EventArgs) Handles btnCalculateValue.Click
If ComboBoxC1L1.SelectedIndex >= 0 Then
Dim val = CInt(ComboBoxC1L1.SelectedValue)
If ComboBoxQC1L1.Text = "ordinaire" Then
LabelPointsC1L1.Text = val.ToString
ElseIf ComboBoxQC1L1.Text = "médiocre" Then
LabelPointsC1L1.Text = (val - 2).ToString
ElseIf ComboBoxQC1L1.Text = "élite" Then
LabelPointsC1L1.Text = (val + 2).ToString
End If
Dim val2 = DirectCast(ComboBoxC1L1.SelectedItem, DataRowView).Row.Field(Of String)("type_unité")
LabelUnitType.Text = val2
End If
Dim totalC1L1 As Integer
totalC1L1 = CInt(TextBoxC1L1.Text) * CInt(LabelPointsC1L1.Text)
LabelTotalC1L1.Text = totalC1L1.ToString
End Sub

RadioButton does not show up when inside a panel within a panel

This is my first question ever, so please spare me if I did something wrong.
I have a small survey form that automatically draw questions and answers from a SQL server table, and create a question label (Label_Questionnaire(i)), a panel to nest all radiobuttons for the answer of each question (Panel_Response(i)), and 3 radiobuttons(yes, no, n/a), named RadioButton_Answers(i)_1 . All questions and answers are inside a big panel (Panel_Survey) to allow user to scroll up and down (around 50 questions).
When I run the program, I can only see questions but none of the radiobuttons are showing. What I did try are:
Use .BringToFront to bring the Panel_Response and all radiobuttons to front.
Change .Parent to Controls.Add . Instead of using .Parent, I use Panel_Survey.Controls.Add(Panel_Response) and Panel_Response.Controls.Add(RadioButton_Answers_1)
Force Panel_Response.Visible = True and all radiobuttons visible = true
(I know it might sound stupid, but I'm out of trick)
How do I make those radiobuttons show up? If not, are there any better designs for this kind of survey form? Thank you for any advice, in advance!
Below is my code:
Protected Overrides Sub OnLoad(e As EventArgs)
Dim PanelCount As Integer
Dim QuestionName As String
Dim Response1 As String
Dim Response2 As String
Dim Response3 As String
Dim InitialX As Integer = Panel_Survey.Left
Dim InitialY As Integer = Panel_Survey.Top
Dim SizeX As Integer = 1000
Dim SizeY As Integer = 25
'Load the survey
Try
'Get a list of questions and answers into array of list
Dim ListofQuestionandAnswers As New List(Of List(Of String))
Dim conn As New SqlClient.SqlConnection
conn.ConnectionString = ConnectionString
Dim CommandString As String = "SELECT [QuestionID], [QuestionName] ,[Response1],[Response2],[Response3] FROM [Question_List] ORDER BY [QuestionID]"
Dim Command As New SqlClient.SqlCommand
Command.CommandText = CommandString
Command.Connection = conn
Dim dr As SqlClient.SqlDataReader
conn.Open()
dr = Command.ExecuteReader
While dr.Read
Dim ls As New List(Of String)
ls.Add(dr.GetValue(0).ToString)
ls.Add(dr.GetValue(1).ToString)
ls.Add(dr.GetValue(2).ToString)
ls.Add(dr.GetValue(3).ToString)
ls.Add(dr.GetValue(4).ToString)
ListofQuestionandAnswers.Add(ls)
End While
conn.Close()
PanelCount = ListofQuestionandAnswers.Count
For i = 0 To ListofQuestionandAnswers.Count - 1
QuestionName = ListofQuestionandAnswers(i)(1)
Response1 = ListofQuestionandAnswers(i)(2)
Response2 = ListofQuestionandAnswers(i)(3)
Response3 = ListofQuestionandAnswers(i)(4)
Dim Label_Questionnaire As New Label
Dim Panel_Response As New Panel
Dim RadioButton_Answers_1 As New RadioButton
Dim RadioButton_Answers_2 As New RadioButton
Dim RadioButton_Answers_3 As New RadioButton
'Condition the label
With Label_Questionnaire
.Parent = Panel_Survey
.Name = "Label_Questionnaire" + i.ToString
.Font = New Font("Calibri", 11, FontStyle.Regular)
.Text = QuestionName
.ForeColor = Color.Black
.Location = New Point(InitialX, InitialY)
.AutoSize = True
End With
'Condition the panel
With Panel_Response
'Panel_Survey.Controls.Add(Panel_Response)
.Parent = Panel_Survey
.Name = "Panel_Questionnaire" + i.ToString
.Location = New Point(InitialX + 880, InitialY)
.Width = 250
.Height = 25
.BringToFront()
End With
Dim j As Integer
Dim h As Integer
j = Panel_Response.Left
h = Panel_Response.Top
'Condition the radiobuttons for answers
With RadioButton_Answers_1
.Parent = Panel_Response
.Name = "RadioButton_Answers" + i.ToString + "_1"
.Font = New Font("Calibri", 11, FontStyle.Regular)
.Text = Response1
.ForeColor = Color.Black
.Location = New Point(j, h)
.AutoSize = True
h += RadioButton_Answers_1.Height
End With
With RadioButton_Answers_2
.Parent = Panel_Response
.Name = "RadioButton_Answers" + i.ToString + "_2"
.Font = New Font("Calibri", 11, FontStyle.Regular)
.Text = Response2
.ForeColor = Color.Black
.Location = New Point(RadioButton_Answers_1.Right, h)
.AutoSize = True
End With
With RadioButton_Answers_3
.Parent = Panel_Response
.Name = "RadioButton_Answers" + i.ToString + "_3"
.Font = New Font("Calibri", 11, FontStyle.Regular)
.Text = Response3
.ForeColor = Color.Black
.Location = New Point(RadioButton_Answers_2.Right, h)
.AutoSize = True
End With
InitialY = InitialY + SizeY + 10
Next
Catch ex As Exception
MessageBox.Show(String.Format("Error: {0}", ex.Message), "Error while creating questions and answers", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Few basic problems here:
You seem to assume that when a control is placed inside a panel, it must be placed at a location relative to the form. It doesn't; it places relative to the Panel which has its own coordinate system starting at 0,0 in the top left of the panel - you initialize j and h (for locations of the radio buttons) to the Left and Top of the panel they're in, but they should be inited to 0,0 if you want the radiobuttons to start at the top left of the panel. If the Panel is placed at 300,300 on a form, and you place a radiobutton inside the panel also at 300,300 (because you copied its left and top) then the radio button will look like it's at 600,600 on the form because its at 300,300 inside a panel that is at 300,300
You only make your panel 250 wide - it's barely wide enough to show a single radio button
You increment h once, by an amount that means the next radiobutton disappears off the bottom of the panel (which is 25 pixels high)
Here:
With Panel_Response
'Panel_Survey.Controls.Add(Panel_Response)
.Parent = Panel_Survey
.Name = "Panel_Questionnaire" + i.ToString
.Location = New Point(InitialX + 880, InitialY)
.Width = 2500
.Height = 25
.BringToFront()
.BackColor = Color.Red
End With
Dim j As Integer
Dim h As Integer
j = 0
h = 0
Paste that over your app code and run it again. I made the panel BackColor red so you can more easily see where the panel is
I guess you need to decide how you want your UI to look. If the radiobuttons are laid out vertically, don't increment X when you add them to the panel (by setting the parent property). Make the panel tall enough to accommodate them (25 px not enough)
Use a FlowLayoutPaanel or TableLayoutPanel instead

How to access several dymanically created Combobox at form load?

I'm creating comboboxes on form load, but the thing is once I have added a new cb I can't access (set value, edit properties, etc) of the prior ones.
See Below Example:
Sub Start_stackoverflow()
Dim strings() As String = {"Green", "Purple", "Red"}
Dim x as integer
For x = LBound(strings) To UBound(strings)
NewDropDown(x,50,100,strings(x),strings(x))
Next x
End Sub
Private Sub NewDropDown(ByVal Number As Integer, ByVal PosX As Integer, ByVal PosY As Integer, ByVal Name As String, ByVal Text As String)
cbComboBox = New ComboBox
cbComboBox.Location = New Point(150, PosY - 4%)
cbComboBox.Name = Number
cbComboBox.ForeColor = Color.White
cbComboBox.BackColor = Color.DarkBlue
cbComboBox.Text = Name
cbComboBox.AutoSize = True
Me.Controls.Add(cbComboBox)
End Sub
So this is what happens, I can create the comboboxes just fine, add the values but if I wanted to edit the combobox Green for example (since it was first) I cant.
Even If I try this:
Sub Test()
UpdateComboBoxCurrentlySelected(Green, MyValueIwantSelected)
End Sub
Sub UpdateComboBoxCurrentlySelected(ByVal SetGrpName As ComboBox, ByVal CurrentItem As String)
SetGrpName.Text = (CurrentItem)
SetGrpName.SelectedText = (CurrentItem)
SetGrpName.SelectedItem = (CurrentItem)
SetGrpName.SelectedIndex = (CurrentItem)
SetGrpName.SelectedValue = (CurrentItem)
End Sub
Can anyone shed some light on this, that way I will know how to do it properly.
Thanks
You either need to hold a reference to the object you want to edit:
' At form level
Private dropdowns As Dictionary(Of String, Combobox) = New Dictionary(Of String, ComboBox)
' Populate from Sub Start_stackoverflow()
Dim dropdown As ComboBox = Nothing
' ...
dropdown = NewDropDown(x,50,100,strings(x),strings(x))
dropdowns.Add(dropdown.Name, dropdown)
' change UpdateComboBoxCurrentlySelected signature to
Sub UpdateComboBoxCurrentlySelected(ByVal SetGrpName As String, ByVal CurrentItem As String)
' get the dropdown by name
Dim dropdown as ComboBox = dropdowns(SetGrpName)
' ...
Or you can iterate over all the controls in the form looking for the one with the name you asked for.
Dim foundControl As ComboBox = Nothing
For Each control As Control In Me.Controls
If control.GetType Is GetType(ComboBox) AndAlso (control.Name = SetGrpName) Then
foundControl = control
End If
Next
If Not Nothing Is foundControl Then
' Do something with your control.
End If

Saving nameless textboxes into Database in VB.NET

I'm a student currently doing my programming coursework. I have created a piece of code which creates text boxes for the user to input the names of tracks from a vinyl. As you can choose the amount of text boxes you create, these text boxes end up not having a name (e.g. textbox1, textbox2...), this makes me unsure of how to send the values of the textboxes to the database table. The table is currently empty and only has one column. Could someone please let me know how I will send these values to the database and also the code to create a new column for the tracks. Here is my current code below:
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Label11.Show()
GroupBox1.Show()
GroupBox1.AutoSize = True
Dim number As Integer
number = TextBox8.Text
Dim boxes(number) As TextBox
Dim newbox As TextBox
For i As Integer = 1 To number
newbox = New TextBox
newbox.Size = New Drawing.Size(100, 20)
newbox.Location = New Point(10, 10 + 25 * (i - 1))
AddHandler newbox.TextChanged, AddressOf TextBox_TextChanged
boxes(i) = newbox
GroupBox1.Controls.Add(newbox)
newbox.Name = ("Trackbox" & i)
Next
End Sub
Your boxes array needs to be declared at form level.
Private boxes() As TextBox
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Label11.Show()
GroupBox1.Show()
GroupBox1.AutoSize = True
Dim number As Integer
'need to insert validation code here to make sure a number is entered in TextBox8
number = Integer.Parse(TextBox8.Text)
ReDim boxes(number)
Dim newbox As TextBox
For i As Integer = 1 To number
newbox = New TextBox
newbox.Size = New Drawing.Size(100, 20)
newbox.Location = New Point(10, 10 + 25 * (i - 1))
AddHandler newbox.TextChanged, AddressOf TextBox_TextChanged
GroupBox1.Controls.Add(newbox)
newbox.Name = ("Trackbox" & i.ToString)
boxes(i) = newbox
Next
End Sub
Then you can reference your text boxes as follows:
MessageBox.Show(boxes(5).Text)

Resources