loop through list box in vb and get a total amount - vb.net

I’m trying to loop through a list of prices on a list box and print the total in a textbox on the form. The loop I have works, but the figures it produces are all wrong!. can any one help me??
the figures look ok but then when i add more items to the list box the total amount goes all wrong.
Public Class f
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'LoftDataSet.Services' table. You can move, or remove it, as needed.
Me.ServicesTableAdapter.Fill(Me.LoftDataSet.Services)
'Loop through all the rows that are in the dataset
For Each dr As DataRow In LoftDataSet.Services.Rows
Dim btn As New Button 'Instantiate a button
btn.Text = dr("service_name").ToString 'UserName is a field in my Users Table
btn.Size = New Size(140, 80)
btn.Tag = dr("ID") 'Here we set the tag to the primary key (ID)
'Since we're using a flowlayoutpanel, we don't need to worry about setting the location property
FlowLayoutPanel1.Controls.Add(btn) 'Add the button to the flow layout panel
AddHandler btn.Click, AddressOf UserClick 'Here we give the button a handler for the click event
Next
End Sub
Public Class Product
Public Property ProductName As String
Public Property ProductCost As Decimal
Public Overrides Function ToString() As String
Return ProductCost & " " & ProductName
'Here you could build a formatted string to the user to include cost
End Function
End Class
'Here we write our method for the click event of the button(s) we created
Dim SelectedProduct As New Product
Private Sub UserClick(ByVal sender As Object, ByVal e As EventArgs)
'We set a filter to the binding source passing it ID=<and whatever is stored in the tag property>
ServicesBindingSource.Filter = "ID = " & DirectCast(sender, Button).Tag.ToString
SelectedProduct.ProductName = DirectCast(sender, Button).Text
SelectedProduct.ProductCost = DirectCast(ServicesBindingSource(0), DataRowView).DataView(0)(2)
ListBox1.Items.Add(SelectedProduct)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
For i As Integer = ListBox1.SelectedIndices.Count - 1 To 0 Step -1
ListBox1.Items.RemoveAt(ListBox1.SelectedIndices(i))
Next
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim aValue As Decimal
For Each item As Product In ListBox1.Items
aValue += CDec(item.ProductCost)
Next
TextBox1.Text = aValue
End Sub
End Class

Cycle through each item using an integer as your count.
For i As Integer = 0 To ListBox1.Items.Count - 1
MsgBox(ListBox1.Items(i).ToString)
Next
Or you can add it to an integer/double value
For i As Integer = 0 To ListBox1.Items.Count - 1
MyInteger += Double.Parse.ListBox1.Items(i).ToString)
Next
MsgBox(MyInteger)
'Now the messagebox will show your total
EDIT:
Do not use ListBo1.Items.Item(i). Access directly through Listbox1.Items(i)

Related

Create list box in runtime and change its color via menu in runtime

I need to write this small program in visual basic, but i face a problem which is i can't change the color or add list form text file during runtime.
this is picture of what i wont to do
http://i62.tinypic.com/30tghh0.png
And this is the code i wrote so far,,
Public Class Form1
Private Sub NewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewToolStripMenuItem.Click
Dim listBox1 As New System.Windows.Forms.ListBox
listBox1.Text = "New List"
listBox1.Location = New Point(25, 25)
listBox1.Size = New Size(380, 280)
Me.Controls.Add(listBox1)
OpenToolStripMenuItem.Enabled = True
SaveToolStripMenuItem.Enabled = True
SaveAsToolStripMenuItem.Enabled = True
CloseToolStripMenuItem.Enabled = True
EditToolStripMenuItem.Enabled = True
End Sub
Private Sub ExirToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExirToolStripMenuItem.Click
End
End Sub
Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
If (OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK) Then
Dim myfile As String = OpenFileDialog1.FileName
Dim allLines As String() = File.ReadAllLines(myfile)
For Each line As String In allLines
ListBox1.Items.Add(line)
Next
End If
End Sub
End Class
The problem as you see is in OpenToolStripMenuItem sub with line ListBox1.Items.Add(line)
is there is no listbox1 because is not created yet.the same with color, save and the rest.
so, please help me to solve it.
Move the declaration of ListBox1 out to the Class level:
Public Class Form1
Private ListBox1 As System.Windows.Forms.ListBox
Private Sub NewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewToolStripMenuItem.Click
ListBox1 = New System.Windows.Forms.ListBox
...
End Sub
...
End Class
*But why create it at run-time like this? You could add it at design-time and set the Visible() property to False. When the New button is clicked, you change Visible() to True. Unless you need a new ListBox to be created each time so you have more than one? If so, how will they be laid out?...

How can I update a label's text when a row in the datagridview is changed?

On my form I have a label (lblBalance) and I have a DGV which is populated from an Access database. If I add, delete or update a row, how can I refresh the label text so it reflects the new balance?
This is my frmMain code so far:
Public Class frmMain
Private Sub TransactionsBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TransactionsBindingNavigatorSaveItem.Click
Me.Validate()
Me.TransactionsBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.CheckingDataSet)
End Sub
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'CheckingDataSet.Transactions' table. You can move, or remove it, as needed.
Me.TransactionsTableAdapter.Fill(Me.CheckingDataSet.Transactions)
lblTotalCredits.Text = BalanceTotal().ToString("c")
End Sub
Private Function BalanceTotal() As Double
Dim tot As Double = 0
Dim i As Integer = 0
For i = 0 To TransactionsDataGridView.Rows.Count - 1
tot = tot + Convert.ToDouble(TransactionsDataGridView.Rows(i).Cells(3).Value)
Next i
Return tot
End Function
End Class
The BindingSource control has a ListChanged event you can try using to update your balance label.
Private Sub TransactionsBindingSource_ListChanged(_
sender As Object, _
e As ListChangedEventArgs) _
Handles TransactionsBindingSource.ListChanged
lblTotalCredits.Text = BalanceTotal().ToString("c")
End Sub

How to programmatically add controls to a form in VB.NET

I am working on an inventory in Visual Basic 2010 Express Edition. I don't know the number of fields that will be necessary for the inventory. My hope was that I could add textboxes/checkboxes/buttons using for loops in the program. Is there a way to add controls to a form without using the toolbox?
Can I add controls by instantiating them in the program?
Yes.
Private Sub MyForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim MyTextbox as New Textbox
With MyTextbox
.Size = New Size(100,20)
.Location = New Point(20,20)
End With
AddHandler MyTextbox.TextChanged, AddressOf MyTextbox_Changed
Me.Controls.Add(MyTextbox)
'Without a help environment for an intelli sense substitution
'the address name and the methods name
'cannot be wrote in exchange for each other.
'Until an equality operation is prior for an exchange i have to work
'on an as is base substituted.
End Sub
Friend Sub MyTextbox_Changed(sender as Object, e as EventArgs)
'Write code here.
End Sub
Dim numberOfButtons As Integer
Dim buttons() as Button
Private Sub MyForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Redim buttons(numberOfbuttons)
for counter as integer = 0 to numberOfbuttons
With buttons(counter)
.Size = (10, 10)
.Visible = False
.Location = (55, 33 + counter*13)
.Text = "Button "+(counter+1).ToString ' or some name from an array you pass from main
'any other property
End With
'
next
End Sub
If you want to check which of the textboxes have information, or which radio button was clicked, you can iterate through a loop in an OK button.
If you want to be able to click individual array items and have them respond to events, add in the Form_load loop the following:
AddHandler buttons(counter).Clicked AddressOf All_Buttons_Clicked
then create
Private Sub All_Buttons_Clicked(ByVal sender As System.Object, ByVal e As System.EventArgs)
'some code here, can check to see which checkbox was changed, which button was clicked, by number or text
End Sub
when you call: objectYouCall.numberOfButtons = initial_value_from_main_program
response_yes_or_no_or_other = objectYouCall.ShowDialog()
For radio buttons, textboxes, same story, different ending.
Public Class Form1
Private boxes(5) As TextBox
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim newbox As TextBox
For i As Integer = 1 To 5 'Create a new textbox and set its properties26.27.
newbox = New TextBox
newbox.Size = New Drawing.Size(100, 20)
newbox.Location = New Point(10, 10 + 25 * (i - 1))
newbox.Name = "TextBox" & i
newbox.Text = newbox.Name 'Connect it to a handler, save a reference to the array & add it to the form control.
AddHandler newbox.TextChanged, AddressOf TextBox_TextChanged
boxes(i) = newbox
Me.Controls.Add(newbox)
Next
End Sub
Private Sub TextBox_TextChanged(sender As System.Object, e As System.EventArgs)
'When you modify the contents of any textbox, the name of that textbox
'and its current contents will be displayed in the title bar
Dim box As TextBox = DirectCast(sender, TextBox)
Me.Text = box.Name & ": " & box.Text
End Sub
End Class
To add controls dynamically to the form, do the following code. Here we are creating textbox controls to add dynamically.
Public Class Form1
Private m_TextBoxes() As TextBox = {}
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
' Get the index for the new control.
Dim i As Integer = m_TextBoxes.Length
' Make room.
ReDim Preserve m_TextBoxes(i)
' Create and initialize the control.
m_TextBoxes(i) = New TextBox
With m_TextBoxes(i)
.Name = "TextBox" & i.ToString()
If m_TextBoxes.Length < 2 Then
' Position the first one.
.SetBounds(8, 8, 100, 20)
Else
' Position subsequent controls.
.Left = m_TextBoxes(i - 1).Left
.Top = m_TextBoxes(i - 1).Top + m_TextBoxes(i - _
1).Height + 4
.Size = m_TextBoxes(i - 1).Size
End If
' Save the control's index in the Tag property.
' (Or you can get this from the Name.)
.Tag = i
End With
' Give the control an event handler.
AddHandler m_TextBoxes(i).TextChanged, AddressOf TextBox_TextChanged
' Add the control to the form.
Me.Controls.Add(m_TextBoxes(i))
End Sub
'When you enter text in one of the TextBoxes, the TextBox_TextChanged event
'handler displays the control's name and its current text.
Private Sub TextBox_TextChanged(ByVal sender As _
System.Object, ByVal e As System.EventArgs)
' Display the current text.
Dim txt As TextBox = DirectCast(sender, TextBox)
Debug.WriteLine(txt.Name & ": [" & txt.Text & "]")
End Sub
End Class
You can get your Button1 location and than increase the Y value every time you click on it.
Public Class Form1
Dim BtnCoordinate As Point
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim btn As Button = New Button
BtnCoordinate.Y += Button1.Location.Y + 4
With btn
.Location = New Point(BtnCoordinate)
.Text = TextBox1.Text
.ForeColor = Color.Black
End With
Me.Controls.Add(btn)
Me.StartPosition = FormStartPosition.CenterScreen
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Button1Coordinate = Button1.Location
End Sub
End Class

vb.net array for slideshow button

Hey all, i am in the middle of trying to figure out how to go about doing this...
I have a form that i call like so:
call frmSlideShow.showWhat("1,4,8,9,11,22")
Each of the numbers represents a different image slide (slide1.png, slide4.png, etc..). The problem i am having is trying to create a "previous" and "next" button to flip through them all. Trying to figure out what number the user is on and going from there and seeing what numbers are still left from the list above that was sent, etc.
If anyone has an idea how i would go about doing that then that would be awesome! :)
UPDATE
here is the code..
Public Sub showWhat(ByVal theNumbers As String)
Dim theNums As String() = theNumbers.Split(New Char() {","c})
Dim theCurNum As String
For Each theCurNum In theNums
Debug.Print(theCurNum)
Next
End Sub
David
Put theNums string array one level up in your code along with an integer variable that keeps track of the current position in the array. Then your next button would check the upperbounds of theNums array to make sure you weren't on the last one. If you weren't, then it would increase the integer variable by one and then you could theNums(intTracker).
Public Class Form1
Dim theNums As String()
Dim intTracker As Integer = 0
Public Sub showWhat(ByVal theNumbers As String)
theNums = theNumbers.Split(New Char() {","c})
intTracker = 0
MsgBox("Currently showing " & theNums(intTracker))
If theNums.GetUpperBound(0) < 1 Then
btnNext.Enabled = False 'Only one number was passed, so disable the next button
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Call showWhat("1,2,3")
End Sub
Private Sub btnLast_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLast.Click
btnNext.Enabled = True
intTracker -= 1
MsgBox("Now on " & theNums(intTracker))
If intTracker = 0 Then
btnLast.Enabled = False 'Disable the button because you're at the beginning
End If
End Sub
Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNext.Click
btnLast.Enabled = True
intTracker += 1
MsgBox("Now on " & theNums(intTracker))
If theNums.GetUpperBound(0) = intTracker Then
btnNext.Enabled = False 'On the last slide, so disable the next button
End If
End Sub
End Class

visual basic List.box question

i have 1 text box and 1 listbox in my VB form.
i want to check duplicate item,compare with textbox.text1 and listbox.list item.
and if textbox.text1 value is '3333' and listbox.list multiple value is '1111' '2222' '3333' '4444'
so how to implement such like duplicate check routine?
so if duplicate detect compare with current text1 value and compare with one of listbox's
value is if detect,want to popup messagebox
thanks in advance
Assuming you are inserting strings into your ListBox you can do this:
Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim x As String
For Each x In ListBox1.Items
If (x = TextBox1.Text) Then
MessageBox.Show("Error")
Return
End If
Next
ListBox1.Items.Add(TextBox1.Text)
End Sub
If it's another type of object that has a property called Value then you need a small change:
Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim x As Foo
For Each x In ListBox1.Items
If (x.Value = TextBox1.Text) Then
MessageBox.Show("Error")
Return
End If
Next
ListBox1.Items.Add(TextBox1.Text)
End Sub
Assuming that the ListBox contains strings, you can use the Contains method of the Items collection to check for matches. Example (make a form with a ListBox called '_theListBox', a TextBox called '_theTextBox' and a Label called '_theLabel'):
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
_theListBox.Items.AddRange(New String() {"aaaa", "bbbb", "cccc", "dddd"})
End Sub
Private Sub _theTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _theTextBox.TextChanged
If ListBoxContainsItem(_theListBox, _theTextBox.Text) Then
_theLabel.Text = "It's a match"
Else
_theLabel.Text = ""
End If
End Sub
Private Function ListBoxContainsItem(ByVal lb As ListBox, ByVal text As String) As Boolean
' check if the string is present in the list '
Return lb.Items.Contains(text)
End Function