Add array values from textboxes and display in a label - vb.net

enter image description here <<< my interface
I am working on something for my exam next week.
I must use Visual Basic. I am supposed to create an array with an integer and string. Integer = distance String = name. there will be 2 textboxes, 2 labels and 2 buttons.
txtname.text, txtdistance.text, lblname, lbldistance, btninputdata and btnshowcontent
btninputdata should be disabled after filling the 30 arrays and making btnshowcontent to be visible and show all the 30 values (inserted values via textboxes) in lblname and lbldistance.
Whereas they both need to be inserted via a textbox store into the array and then using a btnshowcontent the stored array should be displayed on separate labels of name and distance.
My codes:
Public Class Form1
Dim ara(29) As String
Private Sub Form1_Load(sender As Object, e As EventArgs)
End Sub
Private Sub btninputdata_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btninputdata.Click
If txtname.Text <> "" Then
For h As Integer = 0 To 29
If ara(h) = "" Then
ara(h) = txtname.Text
txtname.Clear()
Exit Sub
End If
Label1.Text = ara.ToString()
Next
MsgBox("arry full")
btninputdata.Visible = False
btnshowcontent.Visible = True
End If
End Sub
Private Sub btnshowcontent_Click(sender As Object, e As EventArgs) Handles btnshowcontent.Click
'ListBox1.Items.Clear()
'ListBox1.Items.AddRange(ara)
''Label1.Text &= ara(I) & ""
End Sub
Private Sub Form1_Load_1(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class

You'll want to start with something like this. Not sure how you're really trying to display everything, though. You'd probably want to do validation on the distance field also.
Public Class Form1
Dim Ara As New List(Of MyGroup)
Private Sub btninputdata_Click(sender As Object, e As EventArgs) Handles btninputdata.Click
If txtName.Text.Trim() <> String.Empty Then
Ara.Add(New MyGroup With {.Name = txtName.Text, .Distance = txtDistance.Text})
If Ara.Count >= 30 Then
'Show/Hide buttons
End If
End If
End Sub
End Class
Public Class MyGroup
Public Name As String
Public Distance As Decimal
End Class
If you truly must use an array you can do something like this:
Public Class Form1
Private Ara(29) As MyGroup
Private Sub btninputdata_Click(sender As Object, e As EventArgs) Handles btninputdata.Click
If txtName.Text.Trim() <> String.Empty Then
Dim EmptyLocation = Array.FindIndex(Ara, Function(x) x Is Nothing)
If EmptyLocation > -1 Then
Ara(EmptyLocation) = New MyGroup With {.Name = txtName.Text, .Distance = txtDistance.Text}
Return
End If
'Show/Hide buttons
'Display the results however.
End If
End Sub
End Class
Public Class MyGroup
Public Name As String
Public Distance As Decimal
End Class

Related

How to add user input to array list

the program is supposed to take the text in from the text boxes, combine it into a NewCustomer element, and then display it in a listbox. Below is the code i'm supposed to add to, i've tried lstCustomer.add(txtFirstname.text) but it turned to be an error. Thanks in advance for helping.
Public Class Form1
Private myCustomers As New ArrayList
Public ReadOnly Property SelectedCustomer As Customer
Get
Dim index As Integer = lstCustomer.SelectedIndex
If index <> -1 Then
Return lstCustomer.Items(index)
Else
Return Nothing
End If
End Get
End Property
Public Sub NewCustomer(ByVal fn As String, ByVal ln As String, ByVal a As Integer, ByVal e As String)
Dim temp As Customer
temp.FirstName = fn
temp.LastName = ln
temp.Age = a
temp.Email = e
myCustomers.Add(temp)
Me.lstCustomer.Items.Add(temp)
End Sub
Private Sub BtnTest_Click(sender As Object, e As EventArgs) Handles BtnTest.Click
NewCustomer("Homer", "Simpson", 40, "HSimpson#springf.com")
NewCustomer("Bruce", "Banner", 44, "green#giant.com")
End Sub
Public Sub displayCustomer(ByVal temp As Customer)
Me.TxtName.Text = temp.name
Me.TxtFirstName.Text = temp.FirstName
Me.TxtLastName.Text = temp.LastName
Me.TxtAge.Text = temp.Age
Me.TxtEmail.Text = temp.Email
End Sub
Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles BtnAdd.Click
lstCustomer.add(TxtFirstName.Text And TxtLastName.Text And TxtEmail.Text And TxtAge.Text)
End Sub
I suggest using data binding, this makes it easier to work with the ListBox. First make sure to override ToString in the Customer class to make is displayable in the ListBox
Public Class Customer
Public Property FirstName As String
Public Property LastName As String
Public Property Age As Integer
Public Property Email As String
Public Overrides Function ToString() As String
Return $"{FirstName} {LastName} ({Age}) {Email}"
End Function
End Class
Then we use a List(Of Customer) instead of an ArrayList. The advantage is that the List(Of ) is strongly typed, i.e., its elements are of type Customer, where as the ArrayList has elements of type Object.
Also, we create a wrapper of type BindingList(Of Customer) to wrap our list to enable auto-updating of the ListBox. Example:
Public Class Form1
Dim customers As New List(Of Customer)
Dim customersBinding As BindingList(Of Customer)
Public Sub New()
InitializeComponent()
customersBinding = New BindingList(Of Customer)(customers)
lstCustomer.DataSource = customersBinding
End Sub
Private Sub NewCustomer(ByVal fn As String, ByVal ln As String, ByVal a As Integer, ByVal e As String)
Dim customer As New Customer With {
.FirstName = fn,
.LastName = ln,
.Age = a,
.Email = e
}
customersBinding.Add(customer)
lstCustomer.SelectedItem = customers(customers.Count - 1)
' or lstCustomer.SelectedIndex = customers.Count - 1
End Sub
Private Sub BtnTest_Click(sender As Object, e As EventArgs) Handles BtnTest.Click
NewCustomer("Homer", "Simpson", 40, "HSimpson#springf.com")
NewCustomer("Bruce", "Banner", 44, "green#giant.com")
End Sub
Public Sub DisplayCustomer(ByVal customer As Customer)
TxtFirstName.Text = customer.FirstName
TxtLastName.Text = customer.LastName
TxtAge.Text = customer.Age.ToString()
TxtEmail.Text = customer.Email
End Sub
Private Sub lstCustomer_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstCustomer.SelectedIndexChanged
Dim index As Integer = lstCustomer.SelectedIndex
If index >= 0 Then
DisplayCustomer(customers(index))
End If
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
NewCustomer(TxtFirstName.Text, TxtLastName.Text, CInt(TxtAge.Text), TxtEmail.Text)
End Sub
End Class
In the constructor we create the binding list and set it as data source of the ListBox.
See how Sub NewCustomer only adds the new customer to the binding list. This inserts the customer to the wrapped list as well and at the same time updates the ListBox.
We also automatically select the last inserted customer in the ListBox with
lstCustomer.SelectedItem = customers(customers.Count - 1)
or (easier)
lstCustomer.SelectedIndex = customers.Count - 1
We use the SelectedIndexChanged event to automatically display the customer in the textboxes when the user selects another customer in the listbox.
You could also extend data binding to automatically bind the customer objects to the textboxes. You will find a lot of online tutorials on this subject.

Why is it only displaying one result

This program is supposed to accept in valid candidates for voting, add the names typed in a text box to a list box. In the list box the user may double click on the candidate they choose. After the tally button is clicked a list box displaying the candidates' Names and votes will appear along side the other list box.
My problem is that the lstTallies only displays the last voted candidate.
Below is my code
Public Class Form1
Dim maxVotes As Integer
Dim winner As String
Dim votes() As Integer
Dim index As Integer
Dim candidates As String
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
If Not isValidInput(txtNewCandidate.Text) Then
Exit Sub
End If
lstCandidates.Items.Add(txtNewCandidate.Text)
txtNewCandidate.Clear()
txtNewCandidate.Focus()
ReDim Preserve votes(index)
index += 1
End Sub
Private Function isValidInput(ByRef firstName As String) As Boolean
If IsNumeric(txtNewCandidate.Text) Or txtNewCandidate.Text = "" Then
MsgBox("Please input a valid candidate name.")
txtNewCandidate.Focus()
Return False
Else
Return True
End If
End Function
Private Sub btnTally_Click(sender As Object, e As EventArgs) Handles btnTally.Click
lstTallies.Visible = True
lblTally.Visible = True
lstTallies.Items.Add(lstCandidates.Text & " " & votes(lstCandidates.SelectedIndex))
End Sub
Private Sub lstCandidates_DoubleClick(sender As Object, e As EventArgs) Handles lstCandidates.DoubleClick
If lstCandidates.SelectedIndex = -1 Then
MsgBox("Select a candidate by double-clicking")
End If
votes(lstCandidates.SelectedIndex) += 1
MsgBox("Vote Tallied")
End Sub
End Class
Try this:
Assuming the index of the Candidate and his/her Vote are the same:
Private Sub btnTally_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnTally.Click
lstTallies.Visible = True
lblTally.Visible = True
For i = 0 To lstCandidates.Items.Count - 1
lstTallies.Items.Add(lstCandidates.Items(i).ToString & " - " & votes(i))
Next
End Sub
You cannot get the contents of the ListBox unless you iterate it.

access to new dynamically controls in vb.net

First of all excuse me for my poor grammar and vocabulary :)
please see this source and run it:
Public Class Form1
Public pointX As Integer
Public pointY As Integer = 32
Public dynamicText As TextBox
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
pointX = 330
For i = 1 To 4
dynamicText = New Windows.Forms.TextBox
dynamicText.Name = "T" + Trim(Str(i))
dynamicText.Text = ""
dynamicText.Location = New Point(pointX, pointY)
dynamicText.Size = New Size(100, 20)
Me.Controls.Add(dynamicText)
pointX = pointX - 106
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
pointX = 330
pointY = pointY + 26
For i = 1 To 4
dynamicText = New Windows.Forms.TextBox
dynamicText.Name = "T" + Trim(Str(i))
dynamicText.Text = ""
dynamicText.Location = New Point(pointX, pointY)
dynamicText.Size = New Size(100, 20)
Me.Controls.Add(dynamicText)
pointX = pointX - 106
AddHandler dynamicText.Click, AddressOf printHello1
Next
End Sub
Private Sub printHello1(ByVal sender As System.Object, ByVal e As System.EventArgs)
MsgBox(dynamicText.Name)
If dynamicText.Name = "T1" Then MsgBox("Oh! this is T1")
End Sub
End Class
why If never is not true?!
why MsgBox(dynamicText.Name) always return T4?!
i want all controlls to be access by name or array of names.
please help me thank you. :)
The global variable dynamicText takes the value of the last TextBox added in the loop inside the Button1_Click event. This happens to be the control named T4. You don't really need a global variable in this case. You can cast the sender parameter to a TextBox instance because the sender parameter is the control that has raised the event.
Private Sub printHello1(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim txt = CType(sender, "TextBox")
if txt IsNot Nothing then
MsgBox(txt.Name)
If txt.Name = "T1" Then MsgBox("Oh! this is T1")
End If
End Sub
You also don't need to recreate the controls again in the button click event. The action executed in the form load event is enough (You could add the AddHandler there). Global variables are dangerous, avoid them when possible.
See if this is acceptable. Place a panel at the bottom of your form, set Dock to Bottom, add a single button to the panel and a TextBox. Place a FlowLayoutPanel onto the form, Dock = Fill, AutoScroll = True.
The code below creates the amount of TextBox controls as inputted into TextBox. Each newly created TextBox a click event is added with simple logic.
Form code
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim count As Integer = 0
If Integer.TryParse(TextBox1.Text, count) Then
Dim demo = New TextBoxCreate(FlowLayoutPanel1, "Demos", count)
demo.CreateTextBoxes()
End If
End Sub
End Class
Class code (add a new class to the project, name it TextBoxCreate.vb)
Public Class TextBoxCreate
Public Property TextBoxes As TextBox()
Public Property TextBoxBaseName As String
Public Property TextBoxCount As Integer
Public Property ParentControl As Control
Public Sub New(
ByVal ParentControl As Control,
ByVal BaseName As String,
ByVal Count As Integer)
Me.ParentControl = ParentControl
Me.TextBoxBaseName = BaseName
Me.TextBoxCount = Count
End Sub
Public Sub CreateTextBoxes()
Dim Base As Integer = 10
TextBoxes = Enumerable.Range(0, TextBoxCount).Select(
Function(Indexer)
Dim b As New TextBox With
{
.Name = String.Concat(TextBoxBaseName, Indexer + 1),
.Text = (Indexer + 1).ToString,
.Width = 150,
.Location = New Point(25, Base),
.Parent = Me.ParentControl,
.Visible = True
}
AddHandler b.Click, Sub(sender As Object, e As EventArgs)
Dim tb As TextBox = CType(sender, TextBox)
If tb.Name = TextBoxBaseName & "1" Then
tb.Text = "Got it"
Else
MessageBox.Show(tb.Name)
End If
End Sub
Me.ParentControl.Controls.Add(b)
Base += 30
Return b
End Function).ToArray
End Sub
End Class

Adding Selected Item in a Listbox to a Label in Visual Basic

In the program I'm writing I'm stuck on one of the last steps which is to display an employee's name and salary selected from a listbox in labels (one for the name and one for the salary), but I cannot figure out how to do this. The employee's names and salaries are read in from a file and are placed in the corresponding listboxes on 3 different forms (two that only list names, and one that only lists salaries). On the last form, the user is supposed to select the name of one of the employees and that person's name is supposed to appear in one label (lblName) and their salary is supposed to appear in another label (lblSalary). The names are listed in the selectable listbox, but when I click on one of them nothing happens.
Here is the code I have so far on the main form:
Option Strict On
Imports System.IO
Public Class Main
Private Sub open_Click(sender As Object, e As EventArgs) Handles open.Click
Dim open As New OpenFileDialog
open.Filter = "text files |*.txt|All Files|*.*"
open.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
If open.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim selectedFileName As String = System.IO.Path.GetFileName(open.FileName)
showNames.Enabled = True
showSalaries.Enabled = True
showEmployee.Enabled = True
End If
Dim container As New List(Of Project9)
Using reader As New StreamReader(open.OpenFile)
While Not reader.EndOfStream
Dim employee As New Project9
employee.Name = reader.ReadLine()
employee.Salary = CDbl(reader.ReadLine())
container.Add(employee)
End While
End Using
For Each item As Project9 In container
Names.lstNames.Items.Add(item.Name)
frmTotal.lstShow.Items.Add(item.Name)
Salaries.lstSalaries.Items.Add(item.Salary)
Next
End Sub
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
Me.Close()
Names.Close()
Salaries.Close()
frmTotal.Close()
End Sub
Private Sub showNames_Click(sender As Object, e As EventArgs) Handles showNames.Click
Names.Show()
End Sub
Private Sub showSalaries_Click(sender As Object, e As EventArgs) Handles showSalaries.Click
Salaries.Show()
End Sub
Private Sub showEmployee_Click(sender As Object, e As EventArgs) Handles showEmployee.Click
frmTotal.Show()
End Sub
End Class
Public Class Project9
Dim strName As String
Dim dblSalary As Double
Public Property Name As String
Get
Return strName
End Get
Set(value As String)
strName = value
End Set
End Property
Public Property Salary As Double
Get
Return dblSalary
End Get
Set(value As Double)
If dblSalary < 0 Then
dblSalary = 10
End If
dblSalary = value
End Set
End Property
Public Function computeSalary(intMonths As Integer) As Double
Dim dblTotal As Double = dblSalary * intMonths
Return dblTotal
End Function
End Class
And here's the code from the 4th form which is the one displaying the selected item in labels:
Public Class frmTotal
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
lblName.Text = lstShow.SelectedItem(Name)
Dim intMonths As Integer
intMonths = InputBox("How many months would you like to calculate this employee's salary for?")
End Sub
End Class
Also, how would I be able to make a button visible only after an item has been selected?
Any help would be greatly appreciated.
If you leverage the Datasource property of the listbox you can actually fill the listbox with Project9 items and use the DisplayMember property to choose which property you display in the listbox. This has several advantages. Whenever a listbox item is selected it can be cast as an object of type Project9 and you can display whichever properties you want to the labels. Also the selection is tied together across the listboxes so that a selection in one is the same selection in the others. Here's an example of how that might look:
Dim employees As New List(Of Project9)(
{
New Project9 With {.Name = "A", .Salary = 1000},
New Project9 With {.Name = "B", .Salary = 1200},
New Project9 With {.Name = "C", .Salary = 1100}
})
ListBox1.DataSource = employees
ListBox1.DisplayMember = "Name"
ListBox2.DataSource = employees
ListBox2.DisplayMember = "Salary"
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim selectedemployee = DirectCast(ListBox1.SelectedItem, Project9)
Label1.Text = selectedemployee.Name
Label2.Text = selectedemployee.Salary.ToString
End Sub

looping through datagridview

Mine is a windows app. containing forms named BOM nd BOMSelected..
There is datagridview in BOM which contains checkbox column.. When the user selects checkbox, the selected rows should be seen in the datagridview of other form, SelectedBom..
I have coded but don't get it working.. Some error..
Can you please help ??
Your Help is greatly appreciated..
Here is what i have done !!
Public Class SelectedBom
Private Sub SelectedBom_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'HemDatabase1DataSet4.partno' table. You can move, or remove it, as needed.
'Me.PartnoTableAdapter.Fill(Me.HemDatabase1DataSet4.partno)
Dim count As Integer = 0
For j As Integer = 0 To BOM.dgv1.RowCount - 1
If BOM.dgv1.Rows(j).Cells(0).Value = True Then
Dim ro As New DataGridViewRow
DataGridView2.Rows.Add(ro)
For i As Integer = 0 To BOM.dgv1.ColumnCount - 1
Me.DataGridView2.Rows(count).Cells(i).Value = BOM.dgv1.Rows(j).Cells(i).Value
Next
count += 1
End If
Next
End Sub
End Class
Try,
For Each row As DataGridViewRow In BOM.dgv1.Rows
Dim obj(row.Cells.Count - 1) As Object
For i = 0 To row.Cells.Count - 1
obj(i) = row.Cells(i).Value
Next
Me.DataGridView2.Rows.Add(obj)
Next
EDIT:
Demo:
Add Button1 and DataGridView1 in BOM form
Public Class BOM
Public Class Sample
Public Property Satus As Boolean
Public Property Name As String
Public Property ID As Integer
End Class
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
SelectedBom.Show()
End Sub
Private Sub BOM_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim myList As New List(Of Sample)
myList.Add(New Sample() With {.ID = 1, .Name = "A"})
myList.Add(New Sample() With {.ID = 2, .Name = "B"})
myList.Add(New Sample() With {.ID = 3, .Name = "C"})
DataGridView1.DataSource = myList
End Sub
End Class
Add DataGridView1 in SelectBOM form
Public Class SelectedBom
Private Sub SelectedBom_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim i As Integer = 0
DataGridView1.AutoGenerateColumns = False
DataGridView1.Columns.Add("Name", "Name")
DataGridView1.Columns.Add("No", "No")
For Each row As DataGridViewRow In BOM.DataGridView1.Rows
If DirectCast(row.Cells(0).Value, Boolean) Then
DataGridView1.Rows.Add(row.Cells(1).Value, row.Cells(2).Value)
End If
Next
End Sub
End Class
Maybe instead of using the for each statement, you should instead use:
for istep as integer = 0 to datagridview.rowcount - 2
With the for each syntax, you can't assign a value to the individual row as you walk down the row.