Results 1 to 23 of 23

Thread: Help with a simple beginners program

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Feb 2009
    Posts
    82

    Help with a simple beginners program

    I've created a program with 2 textboxes and a button. The user must enter a value in each textbox. When the button is clicked, a message box pops up showing the sum of the values entered in each textbox.

    Here's the code:

    Code:
    Dim start As Integer
    Dim endnumber As Integer
            
            start = TextBox1.Text
            endnumber = TextBox2.Text
    
           If start > 0 And endnumber > 0 Then
                Dim answer As Integer
                answer = start + endnumber    'Answer becomes the integer in textbox1 + the integer in textbox2
                MsgBox(answer)  'Message box pops up and displays the answer(the sum of textbox1 and textbox2)
            End If
    Here's what i want to add: if both or only one of the textboxes have no value entered in them, i want a message box to pop up and say "Please enter a value." I've tried using the do while statement and also used if statements but i kept getting errors. Can anybody help me out here?

    Thanks

  2. #2
    Discovering Life Siddharth Rout's Avatar
    Join Date
    Feb 2005
    Location
    Mumbai, India
    Posts
    12,001

    Re: Help with a simple beginners program

    vb Code:
    1. Sub aaa()
    2.     Dim start As Integer, endnumber As Integer, answer As Integer
    3.     If Len(Trim(TextBox1.Text)) = 0 Then
    4.         TextBox1.SetFocus
    5.         MsgBox "Please enter a value in 1st Text Box"
    6.         Exit Sub
    7.     ElseIf Len(Trim(TextBox2.Text)) = 0 Then
    8.         TextBox2.SetFocus
    9.         MsgBox "Please enter a value in the 2nd Text Box"
    10.         Exit Sub
    11.     End If
    12.        
    13.     start = TextBox1.Text
    14.     endnumber = TextBox2.Text
    15.    
    16.     '-- This is not the best way to handle calculation
    17.     '-- what if the user enters text in the textbox
    18.     '-- i can give you the answer but I want you to
    19.     '-- figure this out yourself. If you get stuck, ask
    20.     '-- we will help you :)
    21.     If start > 0 And endnumber > 0 Then
    22.         answer = start + endnumber
    23.         MsgBox (answer)
    24.     End If
    25. End Sub
    A good exercise for the Heart is to bend down and help another up...
    Please Mark your Thread "Resolved", if the query is solved


    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Feb 2009
    Posts
    82

    Re: Help with a simple beginners program

    Thanks but it seems like everything is interfering. It's confusing to me since i just started coding not too long ago. For the lines like TextBox1.SetFocus(), it give me the error "'Set Focus is not a member of 'System.Windows.Forms.Textbox.'" I have no idea what that means.

    Also, could you please explain to me what Len,Trim, and Set Focus do?

    Thanks

  4. #4
    Discovering Life Siddharth Rout's Avatar
    Join Date
    Feb 2005
    Location
    Mumbai, India
    Posts
    12,001

    Re: Help with a simple beginners program

    are you using vb6 or vb.net?
    A good exercise for the Heart is to bend down and help another up...
    Please Mark your Thread "Resolved", if the query is solved


    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero

  5. #5
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: Help with a simple beginners program

    That means that you're using VB.NET and should hang on for a bit until a moderator comes along and moves your thread to the VB.NET section

    And meanwhile, turn on Option Strict by simply writing "Option Strict On" (without the quotationmarks) at the top of your code.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  6. #6

    Thread Starter
    Lively Member
    Join Date
    Feb 2009
    Posts
    82

    Re: Help with a simple beginners program

    Quote Originally Posted by Atheist
    That means that you're using VB.NET and should hang on for a bit until a moderator comes along and moves your thread to the VB.NET section

    And meanwhile, turn on Option Strict by simply writing "Option Strict On" (without the quotationmarks) at the top of your code.
    Thanks, what would the strict option do?

  7. #7
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: Help with a simple beginners program

    You can read about option strict here. Basically its good practise to always have option strict enabled, as it, among other things, minimises the chances of unexpected program behaviour.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  8. #8

    Thread Starter
    Lively Member
    Join Date
    Feb 2009
    Posts
    82

    Re: Help with a simple beginners program

    Thanks dude. Do any of you guys know of any good practice programs/codes to make for a beginner like me in VB .NET? I've looked around but wasn't really able to find anything good. I'd appreciate it if someone could find me some or suggest some.

    Could someone also explain to me the purpose of the "For" loop? I have the basic idea of it but I dont really see why anyone would wanna use it.

  9. #9
    Addicted Member
    Join Date
    Dec 2008
    Posts
    164

    Re: Help with a simple beginners program

    i use for loop if i am to deal with numbers (integers), you should probably read the whole book first, miscrosoft got a book on vb.net, you should try it out..... goodluck...

  10. #10
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: Help with a simple beginners program

    Thread moved from 'VB6 and Earlier' forum to 'VB.Net' (VB2002 and later) forum

  11. #11
    Frenzied Member MaximilianMayrhofer's Avatar
    Join Date
    Aug 2007
    Location
    IM IN YR LOOP
    Posts
    2,001

    Re: Help with a simple beginners program

    Since you are doing this in .Net, not vb6, koolsid's code should be modified as such:

    Code:
    Private Sub aaa()
        Dim start, endnumber, answer As Integer
        
        Select Case True
            Case TextBox1.Text.Length = 0
                MessageBox.Show("Please enter a number in the first textbox.")
                Exit Select
            Case TextBox2.Text.Length = 0
                MessageBox.Show("Please enter a number in the second textbox.")
                Exit Select
            Case Else
                start = Integer.Parse(TextBox1.Text)
                endnumber = Integer.Parse(TextBox2.Text)
                
                If start > 0 AndAlso endnumber > 0 Then
                    MessageBox.Show((start + endnumber).ToString())
                End If
                Exit Select
        End Select
    End Sub

  12. #12

    Thread Starter
    Lively Member
    Join Date
    Feb 2009
    Posts
    82

    Re: Help with a simple beginners program

    Quote Originally Posted by MaximilianMayrhofer
    Since you are doing this in .Net, not vb6, koolsid's code should be modified as such:

    Code:
    Private Sub aaa()
        Dim start, endnumber, answer As Integer
        
        Select Case True
            Case TextBox1.Text.Length = 0
                MessageBox.Show("Please enter a number in the first textbox.")
                Exit Select
            Case TextBox2.Text.Length = 0
                MessageBox.Show("Please enter a number in the second textbox.")
                Exit Select
            Case Else
                start = Integer.Parse(TextBox1.Text)
                endnumber = Integer.Parse(TextBox2.Text)
                
                If start > 0 AndAlso endnumber > 0 Then
                    MessageBox.Show((start + endnumber).ToString())
                End If
                Exit Select
        End Select
    End Sub
    Hey thanks, I tried ur code it works fine.

    A few questions about it : In ur "select case" statements, why do u put an "exit select" at the end of each case? What purpose does it serve? Is it necessary?

    In my code I put:
    start = textbox1.text
    endnumber = textbox2.text

    but you put

    start = integer.parse(textbox1.text)
    endnumber = integer.parse(textbox2.text)

    What exactly does the integer.parse do, does it make any difference from mine?

    What does the textbox.text.length work with?

    Another thing I'm unsure about, in your "case else" statement, is the "if then" statement included within it or are they separate?

    Lastly, near the end of ur code, it says: "MessageBox.Show((start + endnumber).ToString())."
    What difference does the ".ToString()" part at the end make?

    Thanks, i know its a lot of questions lol sorry but i'm novice.
    Last edited by knicksfan426; Feb 16th, 2009 at 10:59 AM.

  13. #13
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: Help with a simple beginners program

    If you had tried using your original code with Option Strict On, you'd see why Maximilian is using Integer.Parse and ToString in his code. Basically it explicitly converts a variable from one type to another.

    That said, I think TryParse is alot better suited to be used in this case.

    There is no need to put Exit Select at the end of each case in a Select statement in VB.NET. However in C type languages it is needed to avoid falling through to the next case, so I believe thats where Max got that from.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  14. #14
    Frenzied Member MaximilianMayrhofer's Avatar
    Join Date
    Aug 2007
    Location
    IM IN YR LOOP
    Posts
    2,001

    Re: Help with a simple beginners program

    Haha yea you caught me. Even when I code in VB.Net, I think in C type. So in my head I was writing a switch statement :P

    And I agree that TryParse is a much better option, but I didn't want to spoonfeed him. I was hoping that his next thread would be something like "Oh crap how do I make sure i'm parsing an actual number" so he could learn a little more.

  15. #15
    Addicted Member
    Join Date
    Dec 2006
    Location
    Between Try & Catch
    Posts
    249

    Re: Help with a simple beginners program

    Make sure you wrap a Try/Catch around your parse statements.

    I'd also suggest using TryParse, instead of just Parse because you won't know what's in that textbox until it gets to your routine.
    If my post helped you, please rate it!

    Languages: VB/ASP.NET 2005, C# 2008,VB6
    Databases: Oracle (knowledge not currently in use), DB2

    FROM Customers
    WHERE We_Know_What_We_Want <> DB.Null
    SELECT *
    0 rows returned

  16. #16

    Thread Starter
    Lively Member
    Join Date
    Feb 2009
    Posts
    82

    Re: Help with a simple beginners program

    more questions! lol

    What does the textbox.text.length work with?

    What if both textboxes are empty? How do i get the msgbox to display "Please enter a number in textbox1 and textbox2"?
    I messed around with it a lot but it didn't work. Here's the complete code: I rewrote it a little bit, I'd appreciate it if you'd work off this code that i wrote.
    Code:
    Dim start As Integer, endnumber As Integer, answer As Integer
    
          Select Case True
                Case TextBox1.Text.Length = 0
                    MessageBox.Show("Please enter a number in textbox 1.")
    
                Case TextBox2.Text.Length = 0
                    MessageBox.Show("Please enter a number in textbox 2.")
    
                Case TextBox1.Text.Length = 0 And TextBox2.Text.Length = 0 ' This is where I'm trying to make the messagebox display that message if BOTH text boxes are empty
                    MessageBox.Show("Please enter a number in textbox 1 and 2.")
    
                Case Else
                    start = TextBox1.Text
                    endnumber = TextBox2.Text
                    answer = start + endnumber
    
                    If start >= 0 And endnumber >= 0 Then
                        MessageBox.Show(answer)
                    End If
    Last edited by knicksfan426; Feb 16th, 2009 at 03:22 PM.

  17. #17
    Addicted Member
    Join Date
    Dec 2006
    Location
    Between Try & Catch
    Posts
    249

    Re: Help with a simple beginners program

    With the way your Case statement is set up, it will never reach the third statement. The only ones that will execute will be either of the first two, or the Case Else.

    This is because you are already checking to make sure the first two textboxes are not empty. Therefore, you do not need to check if both are empty.
    If my post helped you, please rate it!

    Languages: VB/ASP.NET 2005, C# 2008,VB6
    Databases: Oracle (knowledge not currently in use), DB2

    FROM Customers
    WHERE We_Know_What_We_Want <> DB.Null
    SELECT *
    0 rows returned

  18. #18

    Thread Starter
    Lively Member
    Join Date
    Feb 2009
    Posts
    82

    Re: Help with a simple beginners program

    GOT IT!
    Code:
       Dim start As Integer, endnumber As Integer, answer As Integer
    
            Select Case True
    
                Case TextBox1.Text.Length = 0 And TextBox2.Text.Length = 0
                    MessageBox.Show("Please enter a number in textbox 1 and 2.")
    
                Case TextBox1.Text.Length = 0
                    MessageBox.Show("Please enter a number in textbox 1.")
    
                Case TextBox2.Text.Length = 0
                    MessageBox.Show("Please enter a number in textbox 2.")
    
                Case Else
                    start = TextBox1.Text
                    endnumber = TextBox2.Text
                    answer = start + endnumber
    
                    If start >= 0 And endnumber >= 0 Then
                        MessageBox.Show(answer)
                    End If
            End Select
    All I had to do was change the order. One thing im still confused about, what does the "True" after "Select Case" mean? Does it work like an "if" statement?

    Now comes my next dilemma. How do i make it recognize text? I assume it will only recognize numbers since the variables are all integers.
    Last edited by knicksfan426; Feb 16th, 2009 at 06:56 PM.

  19. #19
    Frenzied Member MaximilianMayrhofer's Avatar
    Join Date
    Aug 2007
    Location
    IM IN YR LOOP
    Posts
    2,001

    Re: Help with a simple beginners program

    Using the select statement the way I did is just a little trick to analyse several conditional statements cleanly, rather than nesting a bunch of if/else statements.

    Basically the structure of the select statement is something like this:

    Select Case (someprimitivevariable)
    Case (somevalue)
    'Do somethin
    End Select

    What the program does is step down through the possible cases, and compare them. Above it will check if someprimitivevalue=somevalue. If it does, then the case has been satisfied and it will execute the requisite code. In my example, i've simply used a boolean variable with a value of true. One by one, the program evaluates the cases until it reaches the first one that is true.

  20. #20
    Addicted Member
    Join Date
    Dec 2006
    Location
    Between Try & Catch
    Posts
    249

    Re: Help with a simple beginners program

    What do you mean make it recognize text?

    Think about it, "text"box. That's all that's in a textbox. Just because you assign the text to an integer variable, that doesn't mean all the textbox will accept is an integer. However, that DOES mean the variable won't accept anything but an integer.

    This is how the bottom part of your code should look:
    Code:
    Case Else
                 Try
                    'we will attempt to parse the text as integer
                    start = Integer.TryParse(TextBox1.Text)
                    endnumber = Integer.TryParse(TextBox2.Text)
                    'if no errors are thrown because of format exceptions
                    'we can continue processing
                    answer = start + endnumber
    
                    If start >= 0 And endnumber >= 0 Then
                        MessageBox.Show(answer)
                    End If
             Catch formatex as FormatException
             'if the try parse failed, we will show a message
              Messagebox.Show("Please make sure you have a valid number in both  text boxes.")
              Catch ex as Exception
              'we will catch other errors here
               End Try
            End Select
    Try/Catch is your friend. Sure, there is a performance hit for throwing an exception, but there is a much bigger cost for not handling an exception.
    If my post helped you, please rate it!

    Languages: VB/ASP.NET 2005, C# 2008,VB6
    Databases: Oracle (knowledge not currently in use), DB2

    FROM Customers
    WHERE We_Know_What_We_Want <> DB.Null
    SELECT *
    0 rows returned

  21. #21
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: Help with a simple beginners program

    TryParse does not throw an exception if the conversion fails, so you dont need the Try-Catch there. However it does return True/False depending on the success of the conversion so you should do something like this:
    Code:
    Dim start As Integer
    Dim endnumber As Integer
    Dim answer As Integer
    If Integer.TryParse(TextBox1.Text, start) AndAlso Integer.TryParse(TextBox2.Text, endnumber) Then
        answer = start + endnumber
    
        If start >= 0 AndAlso endnumber >= 0 Then
            MessageBox.Show(Cstr(answer))
        Else
            MessageBox.Show("Both values have to be greater than or equal to 0")
        End If
    Else
        MessageBox.Show("Please enter valid integers")
    End If
    If you write the code like this, theres no need for the Select statement.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  22. #22

    Thread Starter
    Lively Member
    Join Date
    Feb 2009
    Posts
    82

    Re: Help with a simple beginners program

    Correct me if im wrong, the tryparse is checking that a valid text has been entered in to the textbox1, which in our case, the text is an integer?

  23. #23
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: Help with a simple beginners program

    Yes, TryParse will make sure the string passed to it represents a valid integer, and if it does not it will return false. However if it does, it will convert the string to an integer, return true, and the second argument you passed to it will contain the converted integer.

    TryParse is a must to use when dealing with user input.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width