Cant get value from VB class - vb.net

I am trying to make a simple, class based calculator in Visual Basic, but when I press the buttons (Add) (Multiply) it shows 0 as the value in the textbox.
Here is my code:
FORM 2:
Public Class Form2
Dim Class2 As part2Class = New part2Class()
Dim Class2b As part2ClassB = New part2ClassB()
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Num1 As Integer = CType(TextBox1.Text, Integer)
Dim Num2 As Integer = CType(TextBox2.Text, Integer)
MessageBox.Show(Class2.Calculate().ToString())
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim Num1 As Integer = CType(TextBox1.Text, Integer)
Dim Num2 As Integer = CType(TextBox2.Text, Integer)
MessageBox.Show(Class2b.Calculate())
End Sub
End Class
part2Class CLASS
Public Class part2Class
Public Property Num1
Public Property Num2
Public Overridable Function Calculate() As Integer
Return Num1 + Num2
End Function
End Class
Part2ClassB
Public Class part2ClassB
Inherits part2Class
Public Overrides Function Calculate() As Integer
Return Num1 * Num2
End Function
End Class
When I put values in the textbox and press ADD/MULIPLY it shows 0 as the value.

You are not assigning the values to the properties of your classes. Try this:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim Num1 As Integer = CType(TextBox1.Text, Integer)
Dim Num2 As Integer = CType(TextBox2.Text, Integer)
Class2b.Num1=Num1
Class2b.Num2=Num2
MessageBox.Show(Class2b.Calculate())
End Sub

If CType fails you will crash your program. I changed it to TryParse which sets the variable in the second parameter (in this case a property of the class) and returns True or False. The AndAlso stops as soon as it reaches a False and proceeds to the Else part of the If
You need to declare your properties with a datatype in your class. See my comment about Option Strict.
Public Class part2Class
Public Property Num1 As Integer
Public Property Num2 As Integer
Public Overridable Function Calculate() As Integer
Return Num1 + Num2
End Function
End Class
Public Class part2ClassB
Inherits part2Class
Public Overrides Function Calculate() As Integer
Return Num1 * Num2
End Function
End Class
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Class2 As part2Class = New part2Class()
Dim message As String
If Integer.TryParse(TextBox1.Text, Class2.Num1) AndAlso Integer.TryParse(TextBox2.Text, Class2.Num2) Then
message = Class2.Calculate().ToString
Else
message = "Please enter a number in both text boxes."
End If
MessageBox.Show(message)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim Class2b As part2ClassB = New part2ClassB()
Dim message As String
If Integer.TryParse(TextBox1.Text, Class2b.Num1) AndAlso Integer.TryParse(TextBox2.Text, Class2b.Num2) Then
message = Class2b.Calculate().ToString
Else
message = "Please enter a number in both text boxes."
End If
MessageBox.Show(message)
End Sub

Related

How to update the value of a public property in all forms? VB.net

This is my code in module1:
Module Module1
Private strMessage As String = Form3.TextBox1.Text
Public Property getMessage() As String
Get
Return strMessage
End Get
Set(ByVal strCustomerFirstName As String)
strMessage = strCustomerFirstName
End Set
End Property
End Module
I use Form3 to assign the value to strMessage in module1:
Public Class Form3
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
getMessage = TextBox1.Text
Form1.Show()
Me.Hide
End Sub
End Class
But when I update the new value in Form3 the value that is displayed in Form1 didn't update at all. How can I update the value without using the me.close() in form1.
Dim numberOfCharactersToDisplay As Integer = 100
Dim scrollingTextSelector As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
scrollingTextSelector = getMessage
Do Until scrollingTextSelector.Length > (getMessage.Length + numberOfCharactersToDisplay)
scrollingTextSelector &= " " & getMessage
Loop End Sub
Private strMessage As String = Form3.TextBox1.Text
Public Property getMessage() As String
Get
Return strMessage
End Get
Set(ByVal strCustomerFirstName As String)
strMessage = strCustomerFirstName
form3.textbox1.text = strMessage
End Set
End Property

Visual Basic - Simple Bank Transaction [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 7 years ago.
Improve this question
I believe everything is working correctly but I cannot get the labels to display the calculated data, don't know where I messed up here. Any help would be very much appreciated.
Imports System.IO
Public Class Form1
Dim decMakeWithdrawal As Decimal
Dim decBalace As Decimal
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
'Close the form
Me.Close()
End Sub
Private Sub btnDeposit_Click(sender As Object, e As EventArgs) Handles btnDeposit.Click
Dim decMakeDeposit As Decimal
'Add Deposit
decMakeDeposit = CDec(InputBox("Please enter deposit if you have any"))
End Sub
Public Sub btnWithdraw_Click(sender As Object, e As EventArgs) Handles btnWithdraw.Click
Dim decBalance As Decimal
decMakeWithdrawal = CDec(InputBox("Please enter an amount to withdraw"))
If decBalance <= 0 Then
MessageBox.Show("Insufficient funds")
End If
End Sub
Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim decIntRate As Decimal
decIntRate = CDec(InputBox("Please enter the interest rate:"))
End Sub
Private Function decintTrans() As Object
Throw New NotImplementedException
End Function
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim decInterTrans As Decimal
Dim decInterest As Decimal
decInterest = CDec(decintTrans())
decInterTrans += 1D
End Sub
End Class
Public Class Transaction
'Create member variables for properties
Public decBalance As Decimal
Private decIntRate As Decimal
Private decInterest As Decimal
Private intTrans As Integer
Private decMakeWithdrawal As Decimal
Private decMakeDeposit As Decimal
Private decInterestEarned As Decimal
'Create property procedures
Public Property Balance As Decimal
Get
Return decBalance
End Get
Set(value As Decimal)
decBalance = value
End Set
End Property
Public Property IntRate As Double
Get
Return decIntRate
End Get
Set(value As Double)
decIntRate = CDec(value)
End Set
End Property
Public Property InterestTotal As Double
Get
Return decInterest
End Get
Set(value As Double)
decInterest = CDec(value)
End Set
End Property
'calculate the amount of interest for the current period
'stores this value in the Interest property, and adds it to the Balance property
Public Sub addInterest(ByVal addInterest As Integer)
decInterestEarned = decBalance * (decIntRate / 12)
End Sub
'add deposit
Public Sub addDeposit(ByVal addDeposit As Decimal)
decMakeDeposit += addDeposit
End Sub
'withdraw
Public Sub subtractWithdrawl(ByVal subtractWithdrawal As Double)
If decMakeWithdrawal >= subtractWith() Then
decMakeWithdrawal = CDec(decMakeWithdrawal - subtractWith())
Else
MessageBox.Show("No sufficient balance")
End If
End Sub
Private Function subtractWith() As Double
Throw New NotImplementedException
End Function
End Class
I feel your code is being complicated by stuff you have added that you are not using at present.
So to simply things, I've cut the extra stuff out and corrected any errors I could see. A lot of tweaking is still needed and like member blackwood states you should validate the values input by the user before processing the data.
Yet still, simply to start you off and set you on the right path, try the code below and don't forget to compare it to your original so you can see where you were going wrong.
Good luck
Option Explicit
Imports System.IO
Public Class Form1
Dim MyTransactor as Transaction
Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim decIntRate As Decimal
MyTransactor = New Transaction()
decIntRate = CDec(InputBox("Please enter the interest rate:"))
MyTransactor.IntRate = decintRate
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
'Close the form
Me.Close()
End Sub
Private Sub btnDeposit_Click(sender As Object, e As EventArgs) Handles btnDeposit.Click
Dim decMakeDeposit As Decimal
decMakeDeposit = CDec(InputBox("Please enter deposit if you have any"))
MyTransactor.addDeposit = decMakeDeposit
End Sub
Public Sub btnWithdraw_Click(sender As Object, e As EventArgs) Handles btnWithdraw.Click
decMakeWithdrawal = CDec(InputBox("Please enter an amount to withdraw"))
MyTransactor.subtractWithdrawl = decMakeWithdrawal
End Sub
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
MyTransactorAddInterest
MessageBox.Show(MyTransactor.InterestEarned & "Interest add to balance. Total balance now is " & MyTranasactor.Balance)
End Sub
End Class
Public Class Transaction
'Create member variables for properties
Public decBalance As Decimal
Private decIntRate As Decimal
Private decInterestEarned As Decimal
'Create property procedures
Public Property Balance As Decimal
Get
Return decBalance
End Get
Set(value As Decimal)
decBalance = value
End Set
End Property
Public Property IntRate As Double
Get
Return decIntRate
End Get
Set(value As Double)
decIntRate = CDec(value)
End Set
End Property
Public Property InterestEarned As Double
Get
Return decInterestEarned
End Get
Set(value As Double)
decInterestEarned = CDec(value)
End Set
End Property
'calculate the amount of interest for the current period
'stores this value in the Interest property, and adds it to the Balance property
Public Sub AddInterest()
decInterestEarned = decBalance * (decIntRate / 12)
decBalance =+ decInterestEarned
End Sub
'add deposit
Public Sub addDeposit(ByVal DepositValue As Decimal)
decBalance=+ DepositValue
End Sub
'withdraw
Public Sub subtractWithdrawl(ByVal WithdrawalValue As Double)
If decBalance >= WithdrawalValue Then
decBalance =- WithdrawalValue
Else
MessageBox.Show("No sufficient balance")
End If
End Sub
End Class

Add a cancel button to input box VB

I have made a simple calculator and I would like to know if you put in a string instead of a double and if you press close or not. The program is a simple calculator where the menu is a box with buttons for addition, subtraction, multiplication, and division. I would like it if you enter a string a messagebox pops up that tells you to enter a number and when you enter an empty message or click cancel it takes you back to the start of the program. Here is the code
Public Class CalcForm
Property num1 As Double = Nothing
Property num2 As Double = Nothing
Private Sub CalcForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Addition_Click(sender As Object, e As EventArgs) Handles Addition.Click
Getnum()
Dim Answer As Double = num1 + num2
MessageBox.Show("The answer is " & Answer, "Answer")
End Sub
Private Sub Subtraction_Click(sender As Object, e As EventArgs) Handles Subtraction.Click
Getnum()
Dim Answer As Double = num1 - num2
MessageBox.Show("The answer is " & Answer, "Answer")
End Sub
Private Sub Multiplication_Click(sender As Object, e As EventArgs) Handles Multiplication.Click
Getnum()
Dim Answer As Double = num1 * num2
MessageBox.Show("The answer is " & Answer, "Answer")
End Sub
Private Sub Division_Click(sender As Object, e As EventArgs) Handles Division.Click
Getnum()
Dim Answer As Double = num1 / num2
MessageBox.Show("The answer is " & Answer, "Answer")
End Sub
Private Sub Getnum()
num1 = InputBox("Enter your first number", "Number 1")
num2 = InputBox("Enter your second number", "Number 2")
End Sub
End Class
Also I don't care about the difference between an empty ok or a cancel. But since I use doubles do I have to make it a string then convert to an double? If I do, how do I detect if the string has letters and ask the user to re-enter their number?
Do you really need your message box?
If you follow Hans Passant's recommendations and start using TextBox, you could simply bind your variable properties and parse and format them.
Have a look at the example below, it is more lines of code but gets you an opportunity to look at binding parsing and formatting.
It is a simple form with your four buttons and 3 text boxes. User cannot "get out" of the TextBox value is not numeric. Should you go for this solution, I would recommend to set the TextBox property for the result to ReadOnly :)
Imports System.Math
Imports System.ComponentModel
Public Class Form1
Implements INotifyPropertyChanged
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Private Sub NotifyPropertyChanged(ByVal info As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
End Sub
Private _num1 As Double
Property num1 As Double
Get
Return _num1
End Get
Set(value As Double)
If (value <> _num1) Then
_num1 = value
NotifyPropertyChanged("num1")
End If
End Set
End Property
Private _num2 As Double
Property num2 As Double
Get
Return _num2
End Get
Set(value As Double)
If (value <> _num2) Then
_num2 = value
NotifyPropertyChanged("num2")
End If
End Set
End Property
Private _Answer As Double
Property Answer As Double
Get
Return _Answer
End Get
Set(value As Double)
If (value <> _Answer) Then
_Answer = value
NotifyPropertyChanged("Answer")
End If
End Set
End Property
Private Sub CalcForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' TextBox for result
TextBox3.ReadOnly = True
Set_bindings()
End Sub
Private Sub Addition_Click(sender As Object, e As EventArgs) Handles Addition.Click
Answer = num1 + num2
End Sub
Private Sub Substraction_Click(sender As Object, e As EventArgs) Handles Substraction.Click
Answer = num1 - num2
End Sub
Private Sub Multiplication_Click(sender As Object, e As EventArgs) Handles Multiplication.Click
Answer = num1 * num2
End Sub
Private Sub Division_Click(sender As Object, e As EventArgs) Handles Division.Click
Answer = num1 / num2
End Sub
Private Sub Set_bindings()
Dim binH As Binding
TextBox1.DataBindings.Clear()
binH = New Binding("Text", Me, "num1", True, DataSourceUpdateMode.OnPropertyChanged)
AddHandler binH.Parse, AddressOf NumParser
AddHandler binH.Format, AddressOf NumFormatter
TextBox1.DataBindings.Add(binH)
TextBox2.DataBindings.Clear()
binH = New Binding("Text", Me, "num2", True, DataSourceUpdateMode.OnPropertyChanged)
AddHandler binH.Parse, AddressOf NumParser
AddHandler binH.Format, AddressOf NumFormatter
TextBox2.DataBindings.Add(binH)
TextBox3.DataBindings.Clear()
binH = New Binding("Text", Me, "Answer", True, DataSourceUpdateMode.Never)
AddHandler binH.Parse, AddressOf NumParser
AddHandler binH.Format, AddressOf NumFormatter
TextBox3.DataBindings.Add(binH)
End Sub
Private Sub NumParser(ByVal sender As Object, ByVal e As ConvertEventArgs)
If IsNumeric(e.Value) Then
e.Value = e.Value
End If
End Sub
Private Sub NumFormatter(ByVal sender As Object, ByVal e As ConvertEventArgs)
e.Value = FormatNum(e.Value)
End Sub
Private Function FormatNum(ByVal x As Double) As String
Dim sFormat As String
sFormat = ""
Select Case Abs(x)
Case 1 To 1000
sFormat = "##0.000"
Case Is > 10000
sFormat = "0.000E+00"
Case Is = 0
sFormat = "#0.0"
Case Is < 0.001
sFormat = "0.000E-00"
Case Is < 1
sFormat = "#0.0000"
End Select
FormatNum = Format(x, sFormat)
End Function
End Class

Cannot get derived class to perfom function

I am working on an assignment where I have to create a base class named Bonus. The class should contain two Public properties: a String property named SalesId and a Double property named Sales. I also have to include a default constructor and a parameterized constructor in the class. Also include a GetBonus method (function) that calculates a salesperson’s bonus using the following formula:
sales* .05
Then create a derived class named PremiumBonus. The derived class’s GetBonu method should calculate the commission as follows:
sales * .05 + (sales – 2500) * .01.
Be sure to include a default constructor and a parameterized constructor in the derived class.
This is what I have so far but its only calculating the Bonus not the PremiumBonus when necessary.
Payroll.vb
Option Explicit On
Option Strict On
Option Infer Off
' base class
Public Class Bonus
'declare properties
Public Property SalesId As String
Public Property Sales As Double
'default constructor
Public Sub New()
_Sales = 0
_SalesId = String.Empty
End Sub
'parameterized constructor
Public Sub New(ByVal strId As String, ByVal dblB As Double)
_Sales = dblB
_SalesId = strId
End Sub
'method to calculate the bonus using formula
Public Overridable Function GetBonus() As Double
'returns the sales person's bonus
Return _Sales * 0.05
End Function
End Class
' derived class
Public Class PremiumBonus
Inherits Bonus
Public Sub New()
MyBase.New()
End Sub
Public Sub New(ByVal dblB As Double, ByVal strId As String)
MyBase.New(CStr(dblB), CDbl(strId))
End Sub
Public Overrides Function GetBonus() As Double
Return MyBase.GetBonus + (Sales - 2500) * 0.01
End Function
End Class
Main Form.vb
Option Explicit On
Option Strict On
Option Infer Off
Public Class frmMain
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub txtSales_Enter(sender As Object, e As EventArgs) Handles txtSales.Enter
txtSales.SelectAll()
End Sub
Private Sub txtSales_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtSales.KeyPress
If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso e.KeyChar <> "." AndAlso e.KeyChar <> ControlChars.Back Then
e.Handled = True
End If
End Sub
Private Sub txtSales_TextChanged(sender As Object, e As EventArgs) Handles txtSales.TextChanged
lblBonus.Text = String.Empty
End Sub
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
' calculates and displays a bonus
' if the sales are over $2500, instantiate a PremiumBonus object
' and then calculate the bonus
' otherwise, instantiate a Bonus object and then calculate the bonus
Dim myBonus As New Bonus
Dim myPremiumBonus As New PremiumBonus
Dim dblSales As Double
If dblSales > 2500 Then
Double.TryParse(txtSales.Text, myPremiumBonus.Sales)
dblSales = myPremiumBonus.GetBonus
Else
Double.TryParse(txtSales.Text, myBonus.Sales)
dblSales = myBonus.GetBonus
End If
' display the bonus
lblBonus.Text = "ID:" & (txtId.Text).PadRight(6) & dblSales.ToString("C2")
End Sub
End Class

String Manipulation by hiding and showing

The idea is simple, if I have a string value "ABCD" then with a ButtonClick event it should randomly reveal a char while others are hidden. i.e, "B*" another click would "AB**" and so on.
So far, my I have been stuck in a for loop.
For Each c As Char In x
y = Random.Next(0, x.IndexOf(c))
Next
I'm still learning VB.NET at this phase.
Public Class Form1
Private _indexes As Integer()
Private _currentIndex As Integer
Private _chars As Char()
Private _template As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim rnd = New Random()
_template = "ABCD"
' Create indexes that are randomly sorted
_indexes = Enumerable _
.Range(0, _template.Length) _
.OrderBy(Function(i) rnd.Next()) _
.ToArray()
'Create an array of chars with stars '****'.
_chars = New String("*"c, _template.Length).ToCharArray()
_currentIndex = 0
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If _currentIndex < _template.Length Then
Dim index As Integer = _indexes(_currentIndex)
_currentIndex += 1
_chars(index) = _template(index)
Dim result As String = New String(_chars)
Label1.Text = result
End If
End Sub
End Class
I have already posted an answer where I focused on the algorithm. The algorithm code was directly integrated into a form. This works but is not a good practice. The code would be more reusable, more understandable and could be tested more easily if it was extracted to a separate class.
Public Class RandomTextRevealer
Private _indexes As Integer()
Private _currentIndex As Integer
Private _chars As Char()
Private _template As String
Private _result As String
Public Sub New(ByVal templateText As String)
Dim rnd = New Random()
_template = templateText
' Create indexes that are randomly sorted
_indexes = Enumerable _
.Range(0, _template.Length) _
.OrderBy(Function(i) rnd.Next()) _
.ToArray()
'Create an array of chars with stars '****'.
_chars = HiddenText.ToCharArray()
_currentIndex = 0
End Sub
Public Function RevealNext() As String
If _currentIndex < _template.Length Then
Dim index As Integer = _indexes(_currentIndex)
_currentIndex += 1
_chars(index) = _template(index)
_result = New String(_chars)
End If
Return _result
End Function
Public ReadOnly Property HiddenText() As String
Get
Return New String("*"c, _template.Length)
End Get
End Property
End Class
We can test the class like this in a little console application, without a form:
Module Programm
Public Sub Main()
Dim revealer = New RandomTextRevealer("Just a test")
Console.WriteLine(revealer.HiddenText)
For i As Integer = 1 To 12
Console.WriteLine(revealer.RevealNext())
Next
Console.ReadKey()
End Sub
End Module
Now we can integrate it in a form like this (I added a Reset-button, in order to be able to repeat the test with different random values):
Public Class Form2
Dim revealer As RandomTextRevealer
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Reset()
End Sub
Private Sub btnReveal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReveal.Click
Label1.Text = revealer.RevealNext()
End Sub
Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReset.Click
Reset()
End Sub
Private Sub Reset()
revealer = New RandomTextRevealer("ABCD")
Label1.Text = revealer.HiddenText
End Sub
End Class
Now our form-code looks much cleaner.