none
Using variables like they are used in any other language RRS feed

  • Question

  • Hey Guys,

    Decided to pick up some Visual Basic tonight. I'm trying to make a simple 'tax' calculator. Select a country (with a combobox) and get a rate that is multiplied by the amount of money entered into another textbox

    I've used mainly python and c++ the last two years so i'm quite used to programming, classes and functions. I can't really seem to figure out how this works in Visual Basic. I'm using a SelectedIndexChanged-event (not sure if it is called that) to get the county selected. Now I want to get the value from the text box and the country when the 'calculate taxes' button is pressed, to calculate the amount of money left and display this in a messagebox. I can open a message box but cannot access values created in the combobox event. Anyone got tips on how to do this? Do I need to make these variables public?




    Wednesday, May 23, 2018 10:37 PM

All replies

  • Well you could use a Dictionary(Of String, Double) and load its key with the country names and the value for the rate. Such as I show in this thread Combo Box Value Display Issues!.

    Below is the code. In the ComboBox's selected index changed event sub the dictionary will return the Value for the Key provided to it. Or perhaps the code will assist you with getting the ComboBox's selected item ToString.

    You shouldn't need to make any variables public unless you are working with multiple classes or modules that need to access public variables. Although global declaration of variables may be necessary. Since you've been programming for awhile you can place Option Strict On at the top of the code window and if any basic errors are in the code they will error. Such as not converting types and such.

    Here's a link to the Visual Basic Guide and the MSDN Library search engine.

    Option Strict On
    
    Public Class Form1
    
        Dim ComboBox1Input As New Dictionary(Of String, Integer)
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Me.Location = New Point(CInt((Screen.PrimaryScreen.WorkingArea.Width / 2) - (Me.Width / 2)), CInt((Screen.PrimaryScreen.WorkingArea.Height / 2) - (Me.Height / 2)))
    
            ComboBox1Input.Add("Weight Training", 70)
            ComboBox1Input.Add("Yoga Class", 80)
            ComboBox1Input.Add("Cardio Training", 95)
            ComboBox1Input.Add("Swimming Lessons", 40)
            ComboBox1Input.Add("Mind and Body Training", 50)
    
            For i = 0 To ComboBox1Input.Count - 1
                ComboBox1.Items.Add(ComboBox1Input.Keys(i))
            Next
    
        End Sub
    
        Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
            TextBox1.Text = CStr(ComboBox1Input(ComboBox1.SelectedItem.ToString))
        End Sub
    
    End Class

    Also use a Code Block for posting code. You can't post images and possibly hyperlinks until your account is verified.


    La vida loca

    Wednesday, May 23, 2018 10:48 PM
  • Hello,

    See the following and read the comments in regards to hard coded values.

    Concrete class for containing a country(s) and note the id property is optional, I tend to do this with tables in databases

    Public Class Country
        Public Property Id() As Integer
        Public Property Name() As String
        Public Property Rate() As Decimal
    
        Public Overrides Function ToString() As String
            Return Name
        End Function
    End Class

    In the form code I show how to get the rate property on selected index changed of the ComboBox and in the button show how to get the current properties of the selected country.

    Public Class Form1
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            '
            ' This is hard coded but recommend reading data from a text file e.g. comma delimited
            ' using TextFieldParser class or read from a database.
            '
            Dim countries As New List(Of Country) From
                    {
                        New Country() With {.Id = 1, .Name = "USA", .Rate = 0.7D},
                        New Country() With {.Id = 2, .Name = "Canada", .Rate = 0.2D}
                    }
    
            ComboBox1.DataSource = countries
    
            AddHandler ComboBox1.SelectedIndexChanged, AddressOf ComboBox1_SelectedIndexChanged
        End Sub
        Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs)
            txtRate.Text = CType(ComboBox1.SelectedItem, Country).Rate.ToString()
        End Sub
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim country As Country = CType(ComboBox1.SelectedItem, Country)
            txtRate.Text = country.Rate.ToString()
            MessageBox.Show($"Name: {country.Name} rate: {country.Rate} id: {country.Id}")
        End Sub
    End Class
    


    Edit

    Here is reading from a file in the executable folder. It need exception handling for imperfect files, I left this out for easy of learning.

    Modified country class for adapting to receiving data from a text file.

    Public Class Country
        Private _isGood As Boolean
        Public ReadOnly Property Good() As Boolean
            Get
                Return _isGood
            End Get
        End Property
    
        Public Sub New(pLine As String())
    
            Try
                Id = CInt(pLine(0))
                Name = pLine(1)
                Rate = CDec(pLine(2))
                _isGood = True
            Catch ex As Exception
                _isGood = False
            End Try
    
        End Sub
        Public Property Id() As Integer
        Public Property Name() As String
        Public Property Rate() As Decimal
    
        Public Overrides Function ToString() As String
            Return Name
        End Function
    End Class
    
     

    Class responsible for reading a comma delimited file

    Public Class Operations
        Public Function Countries() As List(Of Country)
            Dim results = New List(Of Country)
            Dim fileName As String = IO.Path.
                    Combine(AppDomain.
                    CurrentDomain.BaseDirectory, "Countries.txt")
    
            Using myReader As New FileIO.TextFieldParser(fileName)
    
                myReader.TextFieldType = FileIO.FieldType.Delimited
                myReader.SetDelimiters(",")
                Dim currentRow As String()
    
                While Not myReader.EndOfData
                    currentRow = myReader.ReadFields()
                    Dim tempCountry As New Country(currentRow)
                    If tempCountry.Good Then
                        results.Add(tempCountry)
                    End If
                End While
            End Using
    
            Return results
    
        End Function
    
    End Class
    

    Text file

    1,USA,.5
    2,Canada,.4
    3,England,.8

    Revised form code

    Public Class Form1
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim ops = New Operations
    
            ComboBox1.DataSource = ops.Countries
    
            AddHandler ComboBox1.SelectedIndexChanged, AddressOf ComboBox1_SelectedIndexChanged
        End Sub
        Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs)
            txtRate.Text = CType(ComboBox1.SelectedItem, Country).Rate.ToString()
        End Sub
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim country As Country = CType(ComboBox1.SelectedItem, Country)
            txtRate.Text = country.Rate.ToString()
            MessageBox.Show($"Name: {country.Name} rate: {country.Rate} id: {country.Id}")
        End Sub
    End Class
    
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites


    Wednesday, May 23, 2018 10:53 PM
    Moderator
  • Hi JipG01,

    There's nothing wrong with the existing solutions supplied, however, as a new VB.Net user I don't want you to get the impression that things are more complicated than need be.

    There are several ways to get values into the ComboBox... what did you use?  This will determine the most appropriate and direct way to access the value.

    One thing to note is that the SelectedIndexChanged event doesn't actually generate any values.  It simply informs your code that the user has selected a new item.  Within that event handler you can access the ComboBox.SelectedItem to get the underlying value.  The Type of that value will depend on how you loaded the ComboBox and some of its configuration properties.

    In some configurations, you can simply access the ComboBox.Text property or the ComboBox.Value property.  The value property relies on setting the ValueMember property of the ComboBox and loading an object with a matching public property.

    But you can always access the SelectedItem and then cast it into the appropriate type.

    If you can provide us with more detail about how you setup the ComboBox and loaded items into it, we can provide a more simple and direct answer on how to access that value.


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Wednesday, May 23, 2018 11:12 PM
    Moderator
  • JipG01

    The same conceptual as Reed wrote from another point o view. 

    VB was the first real Desktop oriented program language. It was and is handling events in methods.

     

    Until VB6 there was only Windows Forms and it was done by creating collections of Controls. Since version VB7 it is changed that there can be set a handles clause at a method (with the right signature).

    In VC++, VF# and C# this appending to a method is not available, but the handling of an event can there be added to the method (this can also be used alternatively in VB).

    What  never  is changed is that Windows sent messages to active programs. The active program picks it up and executes the method. In your method is used a combobox, that combobox is a class itself, it exist in the Framework and is instanced in your program.

    As a former python programmer this looks probably strange because you are using all kind what you call static classes, which is in .Net terms a kind of instanced object. (If the term shared in VB or Static in C languages is used it means it is done only once at load time of the program)

    The object can have all kind of properties and fields which hold data. 

    Be aware the event can mean the the index is changed, but that does not mean that the value is set. In for instance a WPF combobox this goes weird, but that is as it is.  

    However, to know more of that learn something about OOP, that is not OO what some think and when you use Internet be sure it is about OOP. Many give OO explanations on Internet which is only a part of it. 


    Success
    Cor






    Thursday, May 24, 2018 11:55 AM
  • Thank you, Cor, for providing more insight as to how VB.Net relates to other languages.  For a new VB.Net user coming from C++/Python, this should be very useful.

    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Thursday, May 24, 2018 12:09 PM
    Moderator