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)
Related
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
since i have the code of the auto generated text box
Insert data from auto generated textbox to SQL Server database
i am try to write a code for ensuring of the auto generated text box in FlowLayoutPanel1 contain data
the auto generated text box build depends on the number in Val(Label2.Text) of the real part
and if any text box is null or empty then the process will stop until fill all fields
the auto generated text box will be like this if the Val(Label2.Text)
is equal to 3
so i try this in the save button
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
For k As Integer = 1 To Val(Label2.Text)
If String.IsNullOrEmpty(FlowLayoutPanel1.Controls(i).Text) Then
MsgBox("Error , fill all text box")
Return
Else
UpdateUsers()
i += 1
End If
Next
MsgBox("Done , add all data to database ")
Button3.Enabled = False
End Sub
so i getting error after leave some text box and back to fill it again
and the all of form code is
Imports System.Data.SqlClient
'library for create folders
Imports System.IO
Public Class part
Dim cLeft As Integer = 1
Dim top1 As Integer = 5
Dim i As Integer = 0
Dim path1 As String
Dim cmd As SqlCommand
Public Sub AddNewTextBox()
Dim txt As New System.Windows.Forms.TextBox()
txt.Top = cLeft * 30
txt.Left = 100
'txt.Text = "TextBox " & Me.cLeft.ToString
cLeft = cLeft + 1
txt.ForeColor = Color.White
txt.BackColor = Color.Gray
txt.Font = New Font("Arial", 14.0, FontStyle.Regular)
txt.Size = New Size(350, 31)
txt.Location = New Point(156, 130 + top1)
txt.TextAlign = HorizontalAlignment.Center
FlowLayoutPanel1.Controls.Add(txt)
End Sub
Private Sub part_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'college part number
Label2.Visible = False
'college path folder
Label3.Visible = False
For m As Integer = 1 To Val(Label2.Text)
AddNewTextBox()
top1 = top1 + 35
Next
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.Close()
End Sub
Private Sub UpdateUsers()
Using cn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Hazim M\Desktop\stud_project\stud_project\Database1.mdf;Integrated Security=True;User Instance=True")
Using cmd As New SqlCommand("INSERT INTO college_part ([name],[coll_of_part],[part_path]) Values (#name,#coll_of_part,#part_path);", cn)
If i < Val(Label2.Text) Then
path1 = Label3.Text & "\" & FlowLayoutPanel1.Controls(i).Text.Trim & Date.Now.Year
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = FlowLayoutPanel1.Controls(i).Text
cmd.Parameters.Add("#coll_of_part", SqlDbType.NVarChar).Value = Label1.Text
cmd.Parameters.Add("#part_path", SqlDbType.NVarChar).Value = path1
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
If Not Directory.Exists(path1) Then
Directory.CreateDirectory(path1)
Else
MsgBox("folder is existing")
End If
End If
End Using
End Using
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
For k As Integer = 1 To Val(Label2.Text)
If String.IsNullOrEmpty(FlowLayoutPanel1.Controls(i).Text) Then
MsgBox("Error , fill all text box")
Return
Else
UpdateUsers()
i += 1
End If
Next
MsgBox("Done , add all data to database ")
Button3.Enabled = False
End Sub
End Class
thank u
I think you need to move dim i Integer=0 to local variable in the Button3_click method. ANd Pass i to the UpdateUser call (add the param to UpdateUser). The current global i keeps adding 1 and eventually out of range.
So I am building a Memory Game. This is a 2 part question. I have 16 boxes being used and need to have the numbers 1-8 twice. I have set up each box as a structure and have a random number generator randomly picking a number for a box and then randomly placing a number 1 - 8 into it. Problem I am coming across is this. I am getting repeat numbers for my boxes and more than 2 times for a digit that will be placed in that box, sometimes no sequential number being used all together. How can I make sure all 16 boxes are being created with out having to make code for 16 different instances. Also need to make sure each single digit number between 1-8 is being used and only used twice?
Second part of my question is I am having an issue with making a click event when a user chooses a box. Right now I can't figure out how to associate which box the user clicks on. I don't want to write code for 16 different boxes, link an array to each box and then populate each box that array's guess number. Is there a way I can simplify that code down to something short?
I have included all the code so far.
Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
Structure MemoryBox
Public intBox As Integer
Public intGuess As Integer
Public strGuess As String
End Structure
Private gameScore() As Integer
Private memoryGame(15) As MemoryBox
Dim countLoad As Integer = 0
Dim countScore As Integer = 0
Dim intScore As Integer
Private Sub LoadGame()
'this is where I am using the random numbers to make each box and populate it with a guess
Dim randomGen As New Random
Dim intMemBox As Integer
Dim intMemGuess As Integer
intScore = 0
If countLoad <= 15 Then
intMemBox = randomGen.Next(1, 16)
intMemGuess = randomGen.Next(1, 8)
memoryGame(countLoad).intBox = intMemBox
memoryGame(countLoad).intGuess = intMemGuess
memoryGame(countLoad).strGuess = intMemGuess.ToString
countLoad += 1
End If
End Sub
Private Sub GuessClick()
'trying to use this area for click event for each box click
lblMemory1.BackColor = Color.Green
lblMemory1.Text = memoryGame()
intScore += 1
lblScore.Text = intScore.ToString
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call LoadGame()
End Sub
Private Sub btnNewGame_Click(sender As Object, e As EventArgs) Handles btnNewGame.Click
gameScore(countScore) = intScore
countScore += 1
Dim outFile As IO.StreamWriter
outFile = IO.File.AppendText("score.txt")
outFile.WriteLine(intScore)
outFile.Close()
Call LoadGame()
End Sub
Private Sub btnHighScore_Click(sender As Object, e As EventArgs) Handles btnHighScore.Click
Array.Sort(gameScore)
lblHighScore.Text = gameScore(0).ToString
End Sub
Private Sub btnAllScores_Click(sender As Object, e As EventArgs) Handles btnAllScores.Click
Dim inFile As IO.StreamReader
Dim strInfo As String
If IO.File.Exists("score.txt") Then
inFile = IO.File.OpenText("score.txt")
Do Until inFile.Peek = -1
strInfo = inFile.ReadLine
Loop
inFile.Close()
Else
MessageBox.Show("Can't find the score.txt file", "High Score", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
MessageBox.Show(strInfo, "All Scores", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
End Class
One option is to populate an array with the numbers you want, then randomly shuffle it. Use a loop that runs at least one times the length of the array and use the iterator value as one index and swap it with a randomly chosen index.
Something like this:
Dim memoryGame(15) As MemoryBox
Dim randomarray() As Integer = {1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8}
Dim rnd As New Random(Now.Millisecond)
For I = 0 To 15
Dim randindex As Integer = rnd.Next(0, 16)
Dim temp As Integer = randomarray(I)
randomarray(I) = randomarray(randindex)
randomarray(randindex) = temp
Next
For I = 0 To 15
memoryGame(I).intBox = randomarray(I)
Next
From here simply iterate through the array and assign the values to your boxes
To handle the click events:
Use the same handler for each box. One way is to add a Handles clause for each box. With 16 boxes this could get a little clunky. I would suggest in the load event handler iterate through the boxes and use the AddHandler statement to add the handler to each box. At this point sender will always point to the box that was clicked. It is simply a matter of casting sender as whatever type the box is, to access all the properties of the box.
If the boxes are buttons(Box1, Box2, etc.) it would look something like this:
For Each b As Button In Me.Controls.OfType(Of Button).Where(Function(x) x.Name.StartsWith("Box"))
AddHandler b.Click, AddressOf Button_Click
Next
Private Sub Button_Click(sender As Object, e As EventArgs)
Dim clickedbutton As Button = DirectCast(sender, Button)
'access the properties here
End Sub
Its been nearly a year since I messed with VB, but I am having an issue on my first assignment of the semester which is supposed to be a refresher. What I am supposed to do is make an application that I input a students name, address, GPA, age by textbox, and which year(freshman, sophomore, other) by radio, and classes by checkbox.
Once filled out I need to take that information and have it previewed in a label.text. If it looks right, I need the textbox.text info concatenated into a listbox. No matter what I try or do it either shows String.Array() in the preview or the program crashes at line 57 any help or insight would be appreciated.
Public Class Form1
'CIS259 Spring 2014 Matthew McQuarrie
'Declare Student Data as a String of 9 arrays
Dim StudentData(8) As String
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
'Close application
Me.Close()
End Sub
Private Sub btnReset_Click(sender As Object, e As EventArgs) Handles btnReset.Click
'Clear entire form
txtName.Clear()
txtAddress.Clear()
txtGPA.Clear()
txtAge.Clear()
radFreshman.Checked = False
radSophomore.Checked = False
radOther.Checked = False
chkCIS.Checked = False
chkMath.Checked = False
chkScience.Checked = False
chkHistory.Checked = False
lblPreview.Text = ""
End Sub
Public Sub btnPreview_Click(sender As Object, e As EventArgs) Handles btnPreview.Click
StudentData(0) = txtName.Text
StudentData(1) = txtAddress.Text
StudentData(2) = txtGPA.Text
StudentData(3) = txtAge.Text
'Find which radio button is checked to add to StudentData
If radFreshman.Checked = True Then
StudentData(4) = "Freshman"
ElseIf radSophomore.Checked = True Then
StudentData(4) = "Sophomore"
ElseIf radOther.Checked = True Then
StudentData(4) = "Other"
End If
'Find which check boxes are checked to add to StudentData
If chkCIS.Checked = True Then
StudentData(5) = "CIS"
If chkMath.Checked = True Then
StudentData(6) = "Math"
If chkScience.Checked = True Then
StudentData(7) = "Science"
If chkHistory.Checked = True Then
StudentData(8) = "History"
End If
End If
End If
End If
'Show StudentData ino the text of lblPreview
lblPreview.Text = StudentData(0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8)
End Sub
Private Sub btnStudent_Click(sender As Object, e As EventArgs) Handles btnStudent.Click
'Add StudentData elements to Student list
lstStudents.Items.Add(StudentData(0 & 1 & 2 & 3))
End Sub
End Class
maybe this approach I used here can help, but there a few differences..
my source is database.. I concatenate the fields in the database (the source)
and I display only the text, not the id on the listbox displaymember. you could concatenate the id to the textfield from the source and displya the fullstring contactenated.
'create the adapter
Dim adapterU As New OleDb.OleDbDataAdapter("Select id,nombre+' '+apellido as fullname from users", con)
'create a datatable
Dim datatableU As New DataTable
'bring the info from the adapter (database) into the datatable.
adapterU.Fill(datatableU)
'relate the datasource (datable) to the listbox lsUsers
lsUsers.DataSource = datatableU
lsUsers.ValueMember = "id"
lsUsers.DisplayMember = "fullname"
I have a CSV file that is formatted as (name,number) on each line.
I'm creating an app that loads all names, index(0), into a listbox at form-load and when a name is selected the number, index(1), is displayed in a .textbox.
I start by filling an array and displaying index(0) in the box. No Prob. But when the selected text changes I have problems. If you cant tell I'm new to VB. If I could assign a var to the selected text I could use a while loop but I'm not sure how to assign that. Is there a better way to go about this? Below is my source. Any help would be great.
Public Class Form1
Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each line As String In IO.File.ReadAllLines("MembershipPhone.txt")
Dim myData = line.Split(","c)
Dim mName = myData(0)
Dim mPhone = myData(1)
ListBox1.Items.Add(mName)
Next
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
For Each line As String In IO.File.ReadAllLines("MembershipPhone.txt")
Dim query = line.Split(","c)
Dim mName = query(0)
Dim mPhone = query(1)
TextBox2.Text = mPhone
Next
End Sub