Counter using KeyPress events - vb.net

First time posting here, although I'm a frequent visitor when I'm looking for answers. I am new to VB and programming.
My problem is this. I had this figured out in VBA, but I want to convert my "program" to a standalone executable with VB (using Visual Studio 2015)
I want to keep track of certain keypresses done on a textbox, and so far I figured out something that works, but it seems messy.
Can anyone think of a better way of doing
Public Class Form1
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles TextBox1.KeyPress
Select Case UCase(e.KeyChar) 'For capturing keypresses and adding them
Case "W" : Label3.Text = Val(Label3.Text) + 1
Case "R" : Label4.Text = Val(Label4.Text) + 1
End Select
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
TextBox1.Text = "" 'Clears the text box after each keypress
End Sub
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim WcountA As Integer
Dim RcountA As Integer
Dim WcountB As Integer
Dim RcountB As Integer
Dim Wavg As Single
Dim Ravg As Single
Select Case Button1.Text
Case "Finish A" 'Finishes first count and stores results in labels
WcountA = Convert.ToInt32(Label3.Text)
RcountA = Convert.ToInt32(Label4.Text)
Button1.Text = "Finish B"
Label5.Text = WcountA
Label7.Text = RcountA
TextBox1.Focus()
Label3.Text = ""
Label4.Text = ""
Case "Finish B" 'Finishes second count and stores in labels
WcountB = Convert.ToInt32(Label3.Text)
RcountB = Convert.ToInt32(Label4.Text)
With Button1
.Text = "Finished"
.Enabled = False
End With
Label6.Text = WcountB
Label8.Text = RcountB
Label3.Text = ""
Label4.Text = ""
WcountA = Label5.Text
RcountA = Label7.Text
WcountB = Label6.Text
RcountB = Label8.Text
Wavg = (WcountA + WcountB) / 2
Ravg = (RcountA + RcountB) / 2
MsgBox("W average = " & Wavg & vbNewLine & "R average = " & Ravg)
End Select
End Sub
End Class
On the form I have the textbox that logs the keypress event, labels that increase by 1 with each specific keypess ("W" and "R"), a button that changes its function with each click(finish first count, finish second count) and some labels I had to use to store the first and second count for the final calculation.
Any suggestion will be appreciated.
Thanks in advance!

First of al, you need to take out the counters of the key pres handler like so;
Because they are gone every time the Button1_Click sub ends.
Public Class Form1
Dim WcountA As Integer
Dim RcountA As Integer
Dim WcountB As Integer
Dim RcountB As Integer
Dim Wavg As Single
Dim Ravg As Single
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles TextBox1.KeyPress
Select Case UCase(e.KeyChar) 'For capturing keypresses and adding them
Case "W" : Label3.Text = Val(Label3.Text) + 1
Case "R" : Label4.Text = Val(Label4.Text) + 1
End Select
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
TextBox1.Text = "" 'Clears the text box after each keypress
End Sub
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Select Case Button1.Text
Case "Finish A" 'Finishes first count and stores results in labels
WcountA = Convert.ToInt32(Label3.Text)
RcountA = Convert.ToInt32(Label4.Text)
Button1.Text = "Finish B"
Label5.Text = WcountA
Label7.Text = RcountA
TextBox1.Focus()
Label3.Text = ""
Label4.Text = ""
Case "Finish B" 'Finishes second count and stores in labels
WcountB = Convert.ToInt32(Label3.Text)
RcountB = Convert.ToInt32(Label4.Text)
With Button1
.Text = "Finished"
.Enabled = False
End With
Label6.Text = WcountB
Label8.Text = RcountB
Label3.Text = ""
Label4.Text = ""
WcountA = Label5.Text
RcountA = Label7.Text
WcountB = Label6.Text
RcountB = Label8.Text
Wavg = (WcountA + WcountB) / 2
Ravg = (RcountA + RcountB) / 2
MsgBox("W average = " & Wavg & vbNewLine & "R average = " & Ravg)
End Select
End Sub
End Class

This is what I ended up doing, works better and looks cleaner. Thanks Lectere for pointing me to the right path!
Public Class Form1
Dim WcountA As Integer
Dim RcountA As Integer
Dim WcountB As Integer
Dim RcountB As Integer
Dim Wavg As Single
Dim Ravg As Single
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles TextBox1.KeyPress
Select Case UCase(e.KeyChar) 'For capturing keypresses and adding them
Case "W" : lblWcount.Text = Val(lblWcount.Text) + 1
Case "R" : lblRcount.Text = Val(lblRcount.Text) + 1
Case Convert.ToChar(13) : Button1_Click(sender, e)
End Select
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
TextBox1.Text = "" 'Clears the text box after each keypress
End Sub
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Select Case Button1.Text
Case "Finish A" 'Finishes first count and stores results in variables
If lblWcount.Text = vbNullString Then 'checks for empty values and treats them as 0
WcountA = 0
Else
WcountA = lblWcount.Text
End If
If lblRcount.Text = vbNullString Then 'checks for empty values and treats them as 0
RcountA = 0
Else
RcountA = lblRcount.Text
End If
Button1.Text = "Finish B"
lbl_1.Text = WcountA
lbl_2.Text = RcountA
TextBox1.Focus()
lblWcount.Text = vbNullString
lblRcount.Text = vbNullString
lblcount.Text = "Count B"
Case "Finish B" 'Finishes second count and stores results in variables
lblcount.Text = vbNullString
If lblWcount.Text = vbNullString Then
WcountB = 0
Else
WcountB = lblWcount.Text
End If
If lblRcount.Text = vbNullString Then
RcountB = 0
Else
RcountB = lblRcount.Text
End If
With Button1
.Text = "Reset"
End With
lbl_3.Text = WcountB
lbl_4.Text = RcountB
lblWcount.Text = vbNullString
lblRcount.Text = vbNullString
Wavg = (WcountA + WcountB) / 2
Ravg = (RcountA + RcountB) / 2
MsgBox("W average = " & Wavg & vbNewLine & "R average = " & Ravg)
Button1.Focus()
Case "Reset" 'Resets values
Dim i As Integer
For i = 1 To 4 'clears labels that start with lbl_ (1 through 4)
Dim myLabel As Label = CType(Controls("lbl_" & i), Label)
myLabel.Text = vbNullString
Next
Initial() ' calls initial form state
End Select
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Initial() 'calls initial form state at load up
End Sub
Private Sub Initial() 'initial state sub
lblcount.Text = "Count A"
TextBox1.Focus()
Button1.Text = "Finish A"
End Sub
End Class
I managed to use loops for clearing labels, and also made pressing Enter during the KeyPress event be treated as a button click.
Loving this feeling of accomplishment when I finally figure something out on something new to me! Love pages like this one where one can learn so much!

Related

vb.net access to folder denied

I searched everywhere for this error, changing the manifest file of the program to run as administrator but nothing changed, im making a program for myself to get video streaming links where i put the first part of it in the textbox1 and the second part on the textbox2 these get put together and a number for the episode gets added but when i try to save a txt file with all the links i cant save it because the access is denied.
Imports System
Imports System.IO
Imports System.Text
Public Class Form1
Dim l1 As String
Dim l2 As String
Dim ep As Integer
Dim nEp As Integer
Dim testo As String
Dim path As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Label4.Text = "Link:" & vbCrLf
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
l1 = CStr(TextBox1.Text)
l2 = CStr(TextBox2.Text)
nEp = CInt(TextBox3.Text)
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
If l1 <> "" And l2 <> "" And IsNumeric(nEp) Then
If ep <= 9 Then
For ep = 0 To 9
Label4.Text = Label4.Text + l1 & "0" & ep & l2 & vbCrLf
Next
If ep > 9 Then
For ep = 10 To nEp
Label4.Text = Label4.Text + l1 & ep & l2 & vbCrLf
Next
testo = Label4.Text
FolderBrowserDialog1.RootFolder = Environment.SpecialFolder.DesktopDirectory
If FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
path = FolderBrowserDialog1.SelectedPath
End If
File.Create(FolderBrowserDialog1.SelectedPath).Dispose()
File.WriteAllText(FolderBrowserDialog1.SelectedPath, testo)
End If
End If
Else
MsgBox("Inserisci i dati correttamente!")
End If
End Sub
End Class
The big thing I saw was use a SaveFileDialog rather than a FolderBrowserDialog. But there's a lot more you can clean up, too:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ep As Integer
If String.IsNullOrWhitespace(TextBox1.Text) OrElse
String.IsNullOrWhitespace(TextBox2.Text) OrElse
Not Integer.TryParse(TextBox3.Text, ep) Then
MsgBox("You need to fill the requested inputs!")
Exit Sub
End If
Dim sfd As New SaveFileDialog()
sfd.InitialDirectory = Environment.SpecialFolder.DesktopDirectory
If sfd.ShowDialog() <> Windows.Forms.DialogResult.OK Then Exit Sub
Dim names() As String =
Enumerable.Range(1, ep).
Select(Function(e) String.Format("{0}{1:00}{2}{3}", TextBox1.Text, e, TextBox2.Text, vbCrLf)).
ToArray()
Dim result As String = String.Join("", names)
Label4.Text &= result
File.WriteAllText(sfd.FileName, Label4.Text)
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
End Sub
The meat of the method is this code:
Enumerable.Range(1, ep).
Select(Function(e) String.Format("{0}{1:00}{2}{3}", TextBox1.Text, e, TextBox2.Text, vbCrLf)).
ToArray()
It uses the Enumerable.Range() function to generate a sequence of integers from 1 to the number of episodes parsed earlier into the ep variable from TextBox3. Then it uses the IEnumerable<T>.Select() function to create a projection of those numbers to the desired strings. Select() accepts a delegate argument, which was supplied here as lambda expression. This lambda expression uses String.Format() to put each string together. Specifically, the episode number goes in the {1:00} placeholder, where the :00 portion is a format string to guarantee at least two digits. Then we call .ToArray() to roll it all up in a structure that will be compatible with String.Join().
I Managed to make it work but if i want to use it again without closing the form the button doesnt do anything.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
l1 = CStr(TextBox1.Text)
l2 = CStr(TextBox2.Text)
nEp = CInt(TextBox3.Text)
nomeFile = CStr(TextBox4.Text)
If l1 <> "" And l2 <> "" And IsNumeric(nEp) Then
If nomeFile <> "" Then
If ep <= 9 Then
For ep = 0 To 9
Label4.Text = Label4.Text + l1 & "0" & ep & l2 & vbCrLf
Next
If ep > 9 Then
For ep = 10 To nEp
Label4.Text = Label4.Text + l1 & ep & l2 & vbCrLf
Next
testo = Label4.Text
If FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
path = FolderBrowserDialog1.SelectedPath + "\" + nomeFile + ".txt"
End If
File.Create(path).Dispose()
File.WriteAllText(path, testo)
MsgBox("File created")
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
Label4.Text = ""
End If
End If
Else
MsgBox("File name missing")
End If
Else
MsgBox("You need to fill the requested inputs!")
End If
End Sub

messagebox appeared second time

In my code, when TextBox3 does not have any value, it must show a notice in a MsgBox to enter a value in TextBox1
But when I run it the MsgBoxnotice appears twice in the screen when it should show only once.
Here is my code:
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If TextBox3.Text = Nothing Then
TextBox1.Clear()
MsgBox("Enter Number to Textbox1")
Else
Dim digit As Integer = CInt(TextBox3.Text)
If TextBox1.TextLength = digit Then
Dim fields() As String = ListBox1.Text.Split(";")
Dim idx As Integer = ListBox1.FindString(TextBox1.Text)
If idx <> -1 Then
ListBox1.SelectedIndex = idx
ListBox1.SelectedIndex.ToString(fields(0))
ListBox2.Items.Add(Now() + Space(1) + ListBox1.Text.Substring(0, 13))
PrintDocument1.Print()
Else
TextBox1.Clear()
End If
End If
End If
End Sub
The Issue here is that the event handler gets triggered another time because clearing the textbox1 equals the textbox1_changed event handler to go of. You could as well just disable the textbox till the textbox3 is not nothing anymore.
or a quick solution would be aswell
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If not TextBox1.Text = Nothing AndAlso TextBox3.text = Nothing Then
TextBox1.Clear()
MsgBox("Enter Number to Textbox1")
.............
You are using the wrong event. Textchanged triggers when you clear the textbox as well resulting in two messageboxes.
Use LostFocus instead
Here is the solution,
Public Class Form1
Dim message as boolean = true
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If TextBox3.Text = Nothing Then
If message Then 'show the message as true
message = False 'set the message false for textbox_changed not appear again
Textbox1.Clear()
message = True 'set the message true for next time textbox change appear again
MsgBox("Enter Number to Textbox3")
End If
Else
Dim digit As Integer = CInt(TextBox3.Text)
If TextBox1.TextLength = digit Then
Dim fields() As String = ListBox1.Text.Split(";")
Dim idx As Integer = ListBox1.FindString(TextBox1.Text)
If idx <> -1 Then
ListBox1.SelectedIndex = idx
ListBox1.SelectedIndex.ToString(fields(0))
ListBox2.Items.Add(Now() + Space(1) + ListBox1.Text.Substring(0, 13))
PrintDocument1.Print()
Else
TextBox1.Clear()
End If
End If
End If
End Sub

display datagridview cell data in the textbox in vb.net

i want to display my datagridview1 data in relevant textboxes. when i select any cell in the datagridview1 relevant data should be displayed in textboxes.
here is the code i did
Private Sub DataGridView1_CellClick(ByVal sender As Object, _
ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) _
Handles DataGridView1.CellClick
Dim i As Integer
i = DataGridView1.CurrentRow.Index
Me.Label8.Text = DataGridView1.Item(0, i).Value
Me.TextBox1.Text = DataGridView1.Item(1, i).Value
Me.TextBox2.Text = DataGridView1.Item(2, i).Value
Me.ComboBox1.Text = DataGridView1.Item(3, i).Value
Me.ComboBox2.Text = DataGridView1.Item(4, i).Value
Me.TextBox5.Text = DataGridView1.Item(5, i).Value
Me.TextBox3.Text = DataGridView1.Item(6, i).Value
Me.TextBox4.Text = DataGridView1.Item(7, i).Value
Me.RichTextBox1.Text = DataGridView1.Item(8, i).Value
Me.RichTextBox2.Text = DataGridView1.Item(9, i).Value
Me.Label14.Text = DataGridView1.Item(10, i).Value
End Sub
i did another code here it is
Private Sub DataGridView1_CellContentClick(ByVal sender _
As System.Object, ByVal e As _
System.Windows.Forms.DataGridViewCellEventArgs) _
Handles DataGridView1.CellContentClick
Try
If e.RowIndex >= 0 Then
Dim row As DataGridViewRow
row = Me.DataGridView1.Rows(e.RowIndex)
Label8.Text = row.Cells("id").Value.ToString
TextBox1.Text = row.Cells("firstname").Value.ToString
TextBox2.Text = row.Cells("lastname").Value.ToString
ComboBox1.Text = row.Cells("year").Value.ToString
ComboBox2.Text = row.Cells("month").Value.ToString
TextBox5.Text = row.Cells("gender").Value.ToString
TextBox3.Text = row.Cells("address").Value.ToString
TextBox4.Text = row.Cells("telephone").Value.ToString
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
however both codes are not working they give errors. inside the "" marks represent the column name
can anyone give me the solution in vb.net
Private Sub DataGridView1_CellClick (ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
Dim i As Integer
With DataGridView1
if e.RowIndex >= 0 Then
i = .CurrentRow.Index
tbID.text = .Rows(i).Cells("id").Value.ToString
tbFirstNametext = .Rows(i).Cells("firstname").Value.ToString
tbLastNametext = .Rows(i).Cells("lastname").Value.ToString
tbAddresstext = .Rows(i).Cells("address").Value.ToString
End If
End With
End Sub
Please use this,
Private Sub DataGridView1_CellContentClick_1(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellDoubleClick
namatxt.Text = Me.DataGridView1.SelectedCells(1).Value.ToString
End Sub
How about this?
Private Sub DataGridView1_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
Dim row As DataGridViewRow = DataGridView1.CurrentRow
Me.Label8.Text = row.Cells(0).Value.ToString()
Me.TextBox1.Text = row.Cells(1).Value.ToString()
Me.TextBox2.Text = row.Cells(2).Value.ToString()
Me.ComboBox1.Text = row.Cells(3).Value.ToString()
Me.ComboBox2.Text = row.Cells(4).Value.ToString()
Me.TextBox5.Text = row.Cells(5).Value.ToString()
Me.TextBox3.Text = row.Cells(6).Value.ToString()
Me.TextBox4.Text = row.Cells(7).Value.ToString()
Me.RichTextBox1.Text = row.Cells(8).Value.ToString()
Me.RichTextBox2.Text = row.Cells(9).Value.ToString()
Me.Label14.Text = row.Cells(10).Value.ToString()
End Sub
Use this code, it works fine for me:
Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
If e.RowIndex >= 0 Then
Dim row As DataGridViewRow
row = Me.DataGridView1.Rows(e.RowIndex)
tbID.Text = row.Cells("id").Value.ToString
tbFirstName.Text = row.Cells("firstname").Value.ToString
tbLastName.Text = row.Cells("lastname").Value.ToString
tbAddress.Text = row.Cells("address").Value.ToString
End If
End Sub
replace the names of the columns i have (i.e "id" "firstname" "lastname") etc with the name of your columns.
To navigate through DataGridView rows with up and down keys and show the selected record in textboxes you can use this:
'declare variable
Private DB As New databasenameDataSetTableAdapters.tablenameTableAdapter
'add constructor to your form
Public Sub New()
' This call is required by the designer.
InitializeComponent()
'Setting KeyPreview To True makes sure that the Form1_KeyDown will always
'be called If a key Is pressed,
Me.KeyPreview = True
End Sub
Private Sub form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
Select Case e.KeyCode
'if else statement is there otherwise when going through the rows in grid
'it would show the previous row in textboxes instead of current one
'GetData is a select query you can generate by double clicking the dataset.xsd file in solution explorer
Case Keys.Up
Dim rowUp As Integer = dataGridView.CurrentRow.Index
If (rowUp <= 0) Then
rowUp = 0
Else
rowUp = rowUp - 1
End If
Try
txtBox1.Text = DB.GetData.Rows(rowUp).Item(0).ToString
txtBox2.Text = DB.GetData.Rows(rowUp).Item(1).ToString
txtBox3.Text = DB.GetData.Rows(rowUp).Item(2).ToString
Catch ex As Exception
MsgBox(ex.Message)
End Try
Exit Select
Case Keys.Down
Dim rowDown As Integer = dataGridView.CurrentRow.Index
If (rowDown >= DB.GetData.Rows.Count - 1) Then
rowDown = DB.GetData.Rows.Count - 1
Else
rowDown = rowDown + 1
End If
Try
txtBox1.Text = DB.GetData.Rows(rowDown).Item(0).ToString
txtBox2.Text = DB.GetData.Rows(rowDown).Item(1).ToString
txtBox3.Text = DB.GetData.Rows(rowDown).Item(2).ToString
Catch ex As Exception
MsgBox(ex.Message)
End Try
Exit Select
Another way of doing it use the datagridview CellEnter event
Private Sub DataGridView1_CellEnter(sender As Object, e As EventArgs)
Handles DataGridView1.CellEnter
Dim row As DataGridViewRow = DataGridView1.CurrentRow
txtBox1.Text = row.Cells(0).Value.ToString()
txtBox2.Text = row.Cells(1).Value.ToString(),
End Sub
Private Sub DataGridView1_CellEnter(sender As Object, e As EventArgs)
Handles DataGridView1.CellEnter
Dim row As DataGridViewRow = DataGridView1.CurrentRow
txtBox1.Text = row.Cells(0).Value.ToString()
txtBox2.Text = row.Cells(1).Value.ToString(),
End Sub

Option Strict On Getting items from lstBox using loop and index

Is there a way to assign an item in a list box to a variable at a specific index with a loop with Option Strict On. its givin me the error "Option Strict On Disallows Late Binding." Error is at strSelected = lstCart.SelectedItem(index).ToString()
The loop basically needs to take each item in the list box, remove the first 20 characters(the name) and then trim the rest(the result is a price), then convert it to an integer using tryparse, then add it to the subtotal. After the program does this it displays the price in lblSub.Text
Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
Dim dblSubTotal As Double
Dim dblPrices() As Double = {4.99, 2.49, 6.49, 5.99, 11.99, 8.99, 4.49, 6.99, 0.99, 2.99}
Dim dblShipping As Double
Const SALES_TAX As Double = 0.04
Dim dblTax As Double
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lstCds.Items.Add(("GardenKnomez").PadRight(20) & "- Across The Lawn")
lstCds.Items.Add(("The Pastries").PadRight(20) & "- Escape The Police")
lstCds.Items.Add(("Road Wasp").PadRight(20) & "- B Flat")
lstCds.Items.Add(("Paper Plated").PadRight(20) & "- Just Throw Us Away")
lstCds.Items.Add(("Exploding Bunions").PadRight(20) & "- Walk It Off")
lstCds.Items.Add(("NeverFart").PadRight(20) & "- Be Careful What You Wish For")
lstCds.Items.Add(("Hoth").PadRight(20) & "- In Michigan")
lstCds.Items.Add(("Naked Nation").PadRight(20) & "- Mabe SomeDay")
lstCds.Items.Add(("Poopsa").PadRight(20) & "- Pizza")
lstCds.Items.Add(("Hidden Valley").PadRight(20) & "- It's Only Ranch")
lstCds.SelectedIndex = 0
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim strArtist As String
Dim intIndexSelected As Integer = lstCds.SelectedIndex
If lstCds.SelectedIndex = -1 Then
MessageBox.Show("Please make a selection... preferably Exploding Bunions")
Else
strArtist = lstCds.SelectedItem.ToString
strArtist = strArtist.Remove(20)
strArtist = strArtist.Trim()
lstCart.Items.Add((strArtist).PadRight(20) & dblPrices(intIndexSelected).ToString("C2"))
'Display Sub Total
dblSubTotal += dblPrices(intIndexSelected)
lblSub.Text = dblSubTotal.ToString("C2")
'Display Tax
dblTax = dblSubTotal * SALES_TAX
lblTax.Text = dblTax.ToString("C2")
'Display Shipping
If lstCart.Items.Count >= 5 Then
dblShipping = 5
ElseIf lstCart.Items.Count > 0 AndAlso lstCart.Items.Count < 5 Then
dblShipping = lstCart.Items.Count
End If
lblShipping.Text = dblShipping.ToString("C2")
'Display Total
lblTotal.Text = (dblSubTotal + dblTax + dblShipping).ToString("C2")
lstCds.SelectedIndex = -1
lstCart.SelectedIndex = lstCart.Items.Count - 1
End If
End Sub
Private Sub btnRemove_Click(sender As Object, e As EventArgs) Handles btnRemove.Click
Dim intIndex As Integer
If lstCart.Items.Count = 0 Then
MessageBox.Show("Theres absolutely nothing in your cart, if you want to exit" &
" click ""FILE"" then click ""Exit""", "Discount Bin",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
ElseIf lstCart.SelectedIndex = -1 Then
MessageBox.Show("Are you ok? You have nothing selected in your cart.", "Discount Bin",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
lstCart.Items.RemoveAt(lstCart.SelectedIndex)
lstCds.SelectedIndex = 0
'subtract removed from subtotal
intIndex = lstCart.Items.Count - 1
dblSubTotal = 0
Dim strSelected As String
Dim dblSelected As Double
For index As Integer = 0 To intIndex
strSelected = lstCart.SelectedItem(index).ToString()
strSelected.Remove(0, 20)
strSelected.Trim()
Double.TryParse(strSelected, dblSelected)
dblSubTotal += dblSelected
Next index
lblSub.Text = dblSubTotal.ToString("C2")
'subtract removed from tax
End If
End Sub
Private Sub mnuFileExit_Click(sender As Object, e As EventArgs) Handles mnuFileExit.Click
If lstCart.Items.Count > 0 Then
Dim strPrice As String = lstCart.SelectedItem.ToString
strPrice = strPrice.Remove(0, 20)
strPrice = strPrice.Trim
strPrice.Insert(0, "$"c)
MessageBox.Show("We hope you enjoy your cd's because they're all pretty terrible," &
" especally the one for " & strPrice)
Else
MessageBox.Show("YOU'LL THANK YOURSELF LATER")
End If
Application.Exit()
End Sub
Private Sub mnuFileSave_Click(sender As Object, e As EventArgs) Handles mnuFileSave.Click
Dim outFile As IO.StreamWriter
If lstCart.Items.Count = 0 Then
MessageBox.Show("You dont have any items in your cart lol", "Discount Bin",
MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
Else
outFile = IO.File.CreateText("ThoseCdsYouWishYouNeverBought.txt")
For index As Integer = 1 To lstCart.Items.Count
lstCart.SelectedIndex = index - 1
outFile.WriteLine(lstCart.SelectedItem)
Next
MessageBox.Show("Reciept printed to your bin directory, your gunna need that.", "Discount Bin",
MessageBoxButtons.OK, MessageBoxIcon.Information)
outFile.Close()
Dim result As DialogResult = MessageBox.Show("Do you want to keep shopping?", "Discount Bin",
MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If result = DialogResult.No Then
Application.Exit()
End If
End If
End Sub
Private Sub lstCart_MouseDown(sender As Object, e As MouseEventArgs) Handles lstCart.MouseDown
lstCds.SelectedIndex = -1
End Sub
End Class
this is incorrect:
Dim strSelected As String
For index As Integer = 0 To intIndex
strSelected = lstCart.SelectedItem(index).ToString()
Next index
lblSub.Text = dblSubTotal.ToString("C2")
SelectedItem is a single object, so you cant index it. to loop thru the SelectedItemS:
Dim n As Integer = 0 to lstCart.SelectedItems.Count - 1
strSelected = lstCart.SelectedItems(n)
' this is pointless because you do nothing with it
Next n
You can put class objects in the listbox, in which case when getting them back you need to convert/cast the Item object back to the correct Type (this is usually the case with that error message):
strName = CType(lstCart.SelectedItem, ItemClass).PropertyName
this would convert an object stored as the SelectedItem back to the Class type, so its props can be referenced. your code is a perfect candicate for a class - it would keep the name and price together rather than having to look things up in other arrays. As soon as you sort the listbox, the indicies no longer match and Gnomes points to the price for Garden Weasel
Edit
To remove the selected items:
For n as Integer = lstCart.SelectedItems.Count - 1 To 0 Step -1
' MUST loop backwards
lstCart.Items.Remove(lstCart.SelectedItems(n)
Next n
after the purge, reloop to recalc instead of subtracting.

not accessible in this context because it is 'Private' [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I'm writing some code for a calculator and I keep getting this error. I have the math functions in another class but the variables from form1 are not accessible. Below is my code.
I've also tried changing my Dim variables to public but that also doesn't work.
Public Class Form1
'create a value to keep track of whether the calculation is complete so the calculator can revert to zero for new calculations
Dim state As Integer
'create values to store information on numbers and signs entered as well as the answer returned
Dim one As Double
Dim two As Double
Dim ans As Double
Dim sign As Char
Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'when "Return" or "Enter" Key is selected button 15 is clicked (seems to only work when textbox selected????)
Me.AcceptButton = Button15
'change the title of the form
Me.Text = "Simple Calculator"
'label the buttons logically
Button1.Text = "1"
Button2.Text = "2"
Button3.Text = "3"
Button4.Text = "4"
Button5.Text = "5"
Button6.Text = "6"
Button7.Text = "7"
Button8.Text = "8"
Button9.Text = "9"
Button10.Text = "0"
Button11.Text = "+"
Button12.Text = "-"
Button13.Text = "X"
Button14.Text = "/"
Button15.Text = "Calc"
Button16.Text = "About Me"
Button17.Text = "Clear"
'allows form to revcieve key events
Me.KeyPreview = True
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'create action when button 1 is clicked
'if state is 1 then previous calculation was solved, then clear textbox to allow for new input
If state = 1 Then
TextBox1.Text = ""
'insert 1 into textbox
Dim Int1 As Integer = 1
TextBox1.Text = TextBox1.Text & Int1
'return state of calculator to zero to designate that calculation has NOT been solved
state = 0
Else
'else insert 1 into textbox
Dim Int1 As Integer = 1
TextBox1.Text = TextBox1.Text & Int1
End If
End Sub
' the above function for each numbered button
Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int2 As Integer = 2
TextBox1.Text = TextBox1.Text & Int2
state = 0
Else
Dim Int2 As Integer = 2
TextBox1.Text = TextBox1.Text & Int2
End If
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int3 As Integer = 3
TextBox1.Text = TextBox1.Text & Int3
state = 0
Else
Dim Int3 As Integer = 3
TextBox1.Text = TextBox1.Text & Int3
End If
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int4 As Integer = 4
TextBox1.Text = TextBox1.Text & Int4
state = 0
Else
Dim Int4 As Integer = 4
TextBox1.Text = TextBox1.Text & Int4
End If
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int5 As Integer = 5
TextBox1.Text = TextBox1.Text & Int5
state = 0
Else
Dim Int5 As Integer = 5
TextBox1.Text = TextBox1.Text & Int5
End If
End Sub
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int6 As Integer = 6
TextBox1.Text = TextBox1.Text & Int6
state = 0
Else
Dim Int6 As Integer = 6
TextBox1.Text = TextBox1.Text & Int6
End If
End Sub
Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int7 As Integer = 7
TextBox1.Text = TextBox1.Text & Int7
state = 0
Else
Dim Int7 As Integer = 7
TextBox1.Text = TextBox1.Text & Int7
End If
End Sub
Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int8 As Integer = 8
TextBox1.Text = TextBox1.Text & Int8
state = 0
Else
Dim Int8 As Integer = 8
TextBox1.Text = TextBox1.Text & Int8
End If
End Sub
Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int9 As Integer = 9
TextBox1.Text = TextBox1.Text & Int9
state = 0
Else
Dim Int9 As Integer = 9
TextBox1.Text = TextBox1.Text & Int9
End If
End Sub
Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
If state = 1 Then
TextBox1.Text = ""
Dim Int0 As Integer = 0
TextBox1.Text = TextBox1.Text & Int0
state = 0
Else
Dim Int0 As Integer = 0
TextBox1.Text = TextBox1.Text & Int0
End If
End Sub
Private Sub Button11_Click(sender As Object, e As EventArgs) Handles Button11.Click
'create an action for when addition button is clicked
Try
'when button is clicked dim sign and text in textbox
sign = "+"
one = TextBox1.Text
TextBox1.Text = ""
Catch ex As Exception
TextBox1.Text = "Error" ' if error occurs return error in textbox
state = 1 'if error occurs return state to 1 to allow for new calculation
End Try
End Sub
'repeat the above action for remainder of arithmic functions
Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
Try
'when button is clicked dim sign and text in textbox
sign = "-"
one = TextBox1.Text
TextBox1.Text = ""
Catch ex As Exception
TextBox1.Text = "Error" ' if error occurs return error in textbox
state = 1 'if error occurs return state to 1 to allow for new calculation
End Try
End Sub
Private Sub Button13_Click(sender As Object, e As EventArgs) Handles Button13.Click
Try
sign = "*"
one = TextBox1.Text
TextBox1.Text = ""
Catch ex As Exception
TextBox1.Text = "Error" ' if error occurs return error in textbox
state = 1 'if error occurs return state to 1 to allow for new calculation
End Try
End Sub
Private Sub Button14_Click(sender As Object, e As EventArgs) Handles Button14.Click
Try
sign = "/"
one = TextBox1.Text
TextBox1.Text = ""
Catch ex As Exception
TextBox1.Text = "Error"
state = 1 'if error occurs return state to 1 to allow for new calculation
End Try
End Sub
Private Sub Button15_Click(sender As Object, e As EventArgs) Handles Button15.Click
'run functions based on sign stored during calculation
Try
two = TextBox1.Text
If sign = "+" Then
Calculator2.Math.add()
ElseIf sign = "-" Then
Calculator2.Math.minus()
ElseIf sign = "*" Then
Calculator2.Math.multiply()
ElseIf sign = "/" Then
Calculator2.Math.divide()
End If
'if user attempts to divide by zero return divide by zero error in textbox
If TextBox1.Text = "Infinity" Then
TextBox1.Text = "Divide by Zero Error"
state = 1 'if error occurs return state to 1 to allow for new calculation
End If
Catch ex As Exception
TextBox1.Text = "Error"
state = 1 'if error occurs return state to 1 to allow for new calculation
End Try
End Sub
Private Sub Button16_Click(sender As Object, e As EventArgs) Handles Button16.Click
'create message box that provides information about author
Dim msg = "Student Name: Emily Wong" & vbCrLf & "Student Number: 0692740" ' Define the message you want to see inside the message box.
Dim title = "About Me" ' Define a title for the message box.
Dim style = MsgBoxStyle.OkOnly ' make an ok button for the msg box
Dim response = MsgBox(msg, style, title)
End Sub
Private Sub Button17_Click(sender As Object, e As EventArgs) Handles Button17.Click
'create a clear button to clear textboxes when clicked and reset state of calculator
TextBox1.Text = ""
state = 0
End Sub
And this is my other class
Public Class Math
Inherits Form1
'create funtions for add,sub, multiply, and divide features
Sub add()
ans = one + two 'creates calculation of the entered numbers
TextBox1.Text = ans 'returns answer into the textbox
state = 1 'returns state to 1 to show that calculation has occured
End Sub
Sub minus()
ans = one - two
TextBox1.Text = ans
state = 1
End Sub
Sub multiply()
ans = one * two
TextBox1.Text = ans
state = 1
End Sub
Sub divide()
ans = one / two
TextBox1.Text = ans
state = 1
End Sub
End Class
state is a private variable in Form1. You can't access from code outside of Form1. Your Math class cannot reference state. Remove the calls to state from the Math class code. An outside class should not be changing the state of another object in anycase.
Try this instead:
Public Class accounting
Dim Operand1 As Double
Dim Operand2 As Double
Dim [Operator] As String
These are the button from 1 - 0
Private Sub Button6_Click_1(sender As Object, e As EventArgs) Handles Button9.Click, Button8.Click, Button7.Click, Button6.Click, Button5.Click, Button4.Click, Button19.Click, Button12.Click, Button11.Click, Button10.Click
txtans.Text = txtans.Text & sender.text
End Sub
This button is for period/point
Private Sub Button18_Click(sender As Object, e As EventArgs) Handles Button18.Click
If InStr(txtans.Text, ".") > 0 Then
Exit Sub
Else
txtans.Text = txtans.Text & "."
End If
End Sub
This button is for clear or "C" in calculator
Private Sub Button20_Click(sender As Object, e As EventArgs) Handles Button20.Click
txtans.Text = ""
End Sub
These are for add,subtract,divide, and multiply
Private Sub Buttonadd_Click(sender As Object, e As EventArgs) Handles Button13.Click
Operand1 = Val(txtans.Text)
txtans.Text = ""
txtans.Focus()
[Operator] = "+"
End Sub
Private Sub Buttondivide_Click(sender As Object, e As EventArgs) Handles Button15.Click
Operand1 = Val(txtans.Text)
txtans.Text = ""
txtans.Focus()
[Operator] = "-"
End Sub
Private Sub Buttonsubtract_Click(sender As Object, e As EventArgs) Handles Button16.Click
Operand1 = Val(txtans.Text)
txtans.Text = ""
txtans.Focus()
[Operator] = "*"
End Sub
Private Sub Buttonmultiply_Click(sender As Object, e As EventArgs) Handles Button14.Click
Operand1 = Val(txtans.Text)
txtans.Text = ""
txtans.Focus()
[Operator] = "/"
End Sub
This button is for "=" sign
Private Sub Buttoneequal_Click(sender As Object, e As EventArgs) Handles Button17.Click
Dim Result As Double
Operand2 = Val(txtans.Text)
'If [Operator] = "+" Then
' Result = Operand1 + Operand2
'ElseIf [Operator] = "-" Then
' Result = Operand1 - Operand2
'ElseIf [Operator] = "/" Then
' Result = Operand1 / Operand2
'ElseIf [Operator] = "*" Then
' Result = Operand1 * Operand2
'End If
Select Case [Operator]
Case "+"
Result = Operand1 + Operand2
txtans.Text = Result.ToString("#,###.00")
Case "-"
Result = Operand1 - Operand2
txtans.Text = Result.ToString("#,###.00")
Case "/"
Result = Operand1 / Operand2
txtans.Text = Result.ToString("#,###.00")
Case "*"
Result = Operand1 * Operand2
txtans.Text = Result.ToString("#,###.00")
End Select
txtans.Text = Result.ToString("#,###.00")
End Sub
This button is for backspace effect.
Private Sub Buttondel_Click(sender As Object, e As EventArgs) Handles Button21.Click
If txtans.Text < " " Then
txtans.Text = Mid(txtans.Text, 1, Len(txtans.Text) - 1 + 1)
Else
txtans.Text = Mid(txtans.Text, 1, Len(txtans.Text) - 1)
End If
End Sub
Note that "txtans.text" is the textbox where the user inputs and where the output shows.