Basics Conversion/TryBlock
Basics Conversion/TryBlock
Basics Conversion/TryBlock
Basics Conversion/TryBlock
Basics Conversion/TryBlock
Basics Conversion/TryBlock Basics Conversion/TryBlock Basics Conversion/TryBlock Basics Conversion/TryBlock Basics Conversion/TryBlock Basics Conversion/TryBlock Basics Conversion/TryBlock Basics Conversion/TryBlock
Basics Conversion/TryBlock Basics Conversion/TryBlock
Basics Conversion/TryBlock
Go Back  Xtreme Visual Basic Talk > > > Basics Conversion/TryBlock


Reply
 
Thread Tools Display Modes
  #1  
Old 05-02-2011, 02:32 PM
NewVBProgrammer NewVBProgrammer is offline
Centurion
 
Join Date: Jul 2010
Location: Grand Manan
Posts: 163
Default Basics Conversion/TryBlock


Alright, I'm going back to the basics to play around. Was getting to far over my head, so now I'm back in the sand box, lol.

I have a simple program I'm trying to make to do a widening conversion from a byte to an integer.

form has a text box for both Input, and Output, plus a conversion button.

Code:
Public Class Form1

    Dim myByte As Byte

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load







    End Sub

    Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.Click

        Try
            myByte = txtInPut.Text
            Dim myInteger As Integer

            myInteger = Convert.ToInt16(myByte)
            txtOutPut.Text = myInteger
        Catch ex As InvalidCastException When myByte > 255
            MessageBox.Show("Please enter a value that can be held within the Byte DataType.")
        End Try

        If myByte > 255 Then
            MessageBox.Show("please enter a valid value for the Byte DataType.")
        End If
       


    End Sub
End Class
I'm trying to use a catch block, but I'm not certain how it works exactly, and also tried to use an If statement to avert the issue, but that didn't work either.

When ever user inputs a number greater than what can be held within the Byte data type the program crashes from the run time error.

hahaha.

anyway, haha

This pops up in the window below where the code is typed.

Quote:
A first chance exception of type 'System.OverflowException' occurred in Microsoft.VisualBasic.dll
and an error message pops up in the compiler saying overflow exception was unhandled.
Reply With Quote
  #2  
Old 05-02-2011, 03:24 PM
NewVBProgrammer NewVBProgrammer is offline
Centurion
 
Join Date: Jul 2010
Location: Grand Manan
Posts: 163
Default

I've also tried this, lol. Still not working right...

Code:
Public Class Form1

    Dim myByte As Byte

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load







    End Sub

    Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.Click

        Dim isByte As Boolean = False
        Dim myInteger As Integer

        myByte = txtInPut.Text

        If myByte <= 255 Then
            isByte = True
        End If

        If myByte <= 255 AndAlso isByte = True Then
            myInteger = Convert.ToInt16(myByte)
            txtOutPut.Text = myInteger

        Else
            MessageBox.Show("you have enterted characters not validly held in the Byte DataType.")
        End If
Reply With Quote
  #3  
Old 05-02-2011, 03:59 PM
AtmaWeapon's Avatar
AtmaWeaponBasics Conversion/TryBlock AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

Byte is a type that ranges from 0-255. It can never be > 255. So this statement is sort of superfluous:
Code:
Catch ex As InvalidCastException When myByte > 255
myByte will only ever be < 255, so this catch statement can't execute. So whatever exception gets thrown is not caught. Note that it's System.OverflowException, not InvalidCastException. That tells you you're looking at the wrong thing.

Filters on Catch blocks are a neat feature of VB, but they're for advanced cases where you want to catch an exception in some cases and ignore it in others. This is quite rare. An overflow is usually a serious error, so there's no need to restrict when you try to catch it.

Anyway, let's step back and take it one line at a time. Usually when an exception is thrown it tells you which line threw it; that helps. So we'll start with the first one.
Code:
myByte = txtInPut.Text
That's got a lot going wrong with it. First things first: turn on Option Strict. Drop whatever you're doing and turn it on. You can do this several ways, a quick web search should reveal how. (The easiest way is to put "Option Strict On" somewhere at the top of the file, usually after Imports statements I think. If you put it in the wrong place the compiler whines and tells you which one is right.)

Why turn that on? It doesn't allow narrowing conversions unless you explicitly make them. Unexpected narrowing conversions are usually a mistake. You've got one on this line of code. What is it? Think about your data types.

txtInPut.Text is a String. myByte is a Byte. While it's possible to convert "3" to a Byte with no loss, you can't convert "256" or "123456789" or "Three" to a Byte. Since there are values of String that cannot be represented by Byte, all String to Byte conversions are narrowing. This is where your overflow exception happens.

How would you solve it? Well, I say go read about converting strings to numbers; I spent a lot of time on that post. You don't have to read the whole thing because I'll discuss some stuff in this thread.

Let's say you didn't read it yet. You could do this:
Code:
Dim value As Byte
Try
    value = CByte(txtInPut.Text)
Catch ex As OverflowException
    MessageBox.Show("That was too big!")
End Try
That's an explicit conversion, and when/if the overflow happens you'll be ready for it. But you won't be able to catch situations like "Three", which would likely throw the InvalidCastException you're talking about. That's what my article tries to cover. You could use Byte.TryParse() and be prepared for anything. You lose the ability to say *exactly* what went wrong, but that's relatively easy to do later. Usually it's good enough to tell a user "I want 0-255, that isn't it."
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #4  
Old 05-02-2011, 04:46 PM
NewVBProgrammer NewVBProgrammer is offline
Centurion
 
Join Date: Jul 2010
Location: Grand Manan
Posts: 163
Default

Quote:
Byte is a type that ranges from 0-255. It can never be > 255. So this statement is sort of superfluous
lol I never noticed that. The overflow exception worked perfectly. How would you go about handling if the user put in letter characters though? That would be the last bug to catch in this I'd say.
Reply With Quote
  #5  
Old 05-02-2011, 07:08 PM
NewVBProgrammer NewVBProgrammer is offline
Centurion
 
Join Date: Jul 2010
Location: Grand Manan
Posts: 163
Default

in addition to figuring out these conversions. I've added a couple of text boxes and a button to add a byte to an integer with the value of 2..

It's working, but I'm still getting different runtime errors. One is that string cannot be converted to a byte..

here's the code so far..

Code:
Option Strict On
Public Class Form1

    Dim myByte As Byte

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load







    End Sub

    Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.Click

        If txtInPut.Text = "" Then
            MessageBox.Show("you have to enter a number to convert.")
        End If

        Try
            myByte = CByte(txtInPut.Text)
        Catch ex As OverflowException
            MessageBox.Show("that number was too big")
        End Try


        Dim myInteger As Integer

        myInteger = Convert.ToInt16(myByte)
        txtOutPut.Text = CStr(myInteger)


        If myByte > 255 Then
            MessageBox.Show("please enter a valid value for the Byte DataType.")
        End If
        



    End Sub

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click

        Dim integerToAdd As Integer = 2

        If txtInput2.Text = "" Then
            MessageBox.Show("You have to enter a byte to be added to the integer")
        End If

        myByte = CByte(txtInput2.Text)

        txtOutPut2.Text = CStr(myByte + CByte(integerToAdd))

        

    End Sub
End Class

I guess my goal here is to make a sound program that doesn't put out an error. Still things are beyond me, lol.
Reply With Quote
  #6  
Old 05-02-2011, 09:08 PM
CodeCruncher CodeCruncher is offline
Junior Contributor
 
Join Date: Jul 2006
Posts: 355
Default

First make this page you new best friend... Note different versions of VB and different programming languages may give you different results for the same data type http://msdn.microsoft.com/en-us/libr...v=VS.100).aspx

Now... What data are you entering into which text box? I tried it with integers and didn’t get an error. If you are trying to enter a letter or some other non integer character into txtInPut.text then it will throw up an error of “Conversion from string "a" to type 'Byte' is not valid.”

So the question is how do we avoid this error rather than fixing it? A letter is never going to equal an integer (unless of course you perform a Hex conversion on it, but that is beside the point). What we need to do is check to see if it is a valid data type before it is offered to the “convert” button. Not sure if you have done any data error checking before but if not now is the time to learn...

What we need to do is check to make sure the data is in fact the data type we are expecting. This is a bit of code I wrote (for a program I am still only part way through) to make sure that the value being offer to the text box is indeed what it is expecting, if we eliminate the wrong data being tested it won’t throw up an error like trying to convert a string to a number.

(lol just trying to make sense of what I wrote myself before I post it )

The function below is used for multiple text boxes since the check I want to perform is the same, here is an example of one of the easier text boxes I am performing the check on.

What I am trying to do here is calculate CdA which is determined by multiplying Cd (Co-efficency Drag) by the frontal area of a vehicle, but I want to make sure that the values are right before I try doing the multiplication.

You will note I am using a single decimal point so the testing is more complicated that if you were just using an integer. You could take out checking for double decimal points etc since you are only going to let number 0-9 past.

Code:
Dim blnSkipMe As Boolean
Dim strValid As String = "0123456789."
Dim strValidOfferingReturn As String

Private Sub tbCd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbCd.Click
        tbCd.SelectionStart = tbCd.TextLength
End Sub

Private Sub tbCd_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbCd.TextChanged

        If blnSkipMe = True Then Exit Sub
        strValidOfferingReturn = ValidateOffering(sender.text)
        blnSkipMe = True
        If Not strValidOfferingReturn = tbCd.Text Then tbCd.Text = strValidOfferingReturn
        blnSkipMe = False
        If Val(Me.tbCd.Text) <> 0 And Val(Me.lblFrontArea.Text) <> 0 Then
            Me.lblCdA.Text = Me.tbCd.Text * Me.lblFrontArea.Text
        Else
            Me.lblCdA.Text = ""
        End If
        tbCd.SelectionStart = tbCd.TextLength

End Sub

Public Function ValidateOffering(ByVal sender As System.Object) As String

        If sender = "" Then
            ValidateOffering = sender
            Exit Function
        End If
        If strValid.Contains(sender.substring(sender.Length - 1, 1)) = True Then
            If InStr(strValid, sender.substring(sender.Length - 1, 1)) = 11 Then
                Dim bytNonNumber As Byte = 0
                For bytC2 = 0 To sender.length - 1
                    If sender.substring(bytC2, 1) = "." Then bytNonNumber += 1
                    If bytNonNumber > 1 Then
                        MsgBox("Only one decimal point allowed.")
                        ValidateOffering = sender.substring(0, sender.Length - 1)
                        Exit Function
                    End If
                Next
            End If
            If sender = "00" Then
                MsgBox("Adding leading zeros helps nothing, it's still zero.")
                ValidateOffering = sender.substring(0, sender.Length - 1)
                Exit Function
            End If
            If sender = "0.0" Or sender = ".0" Or sender = "-0.0" Or sender = "-.0" Then
                MsgBox("No smaller than a tenth allowed")
                ValidateOffering = sender.substring(0, sender.Length - 1)
                Exit Function
            End If
            'Add some upper and lower value limits later
            ValidateOffering = sender
        Else
            MsgBox("Please enter 0-9 & . only")
            ValidateOffering = sender.substring(0, sender.Length - 1)
        End If

    End Function
Reply With Quote
  #7  
Old 05-02-2011, 10:09 PM
AtmaWeapon's Avatar
AtmaWeaponBasics Conversion/TryBlock AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

Quote:
Originally Posted by NewVBProgrammer View Post
lol I never noticed that. The overflow exception worked perfectly. How would you go about handling if the user put in letter characters though? That would be the last bug to catch in this I'd say.
Well, if you're just using CByte() I'd expect an InvalidCastException. You could have figured this out yourself: just let the code run and see which exception you get. (Usually this is in the documentation, but for CByte() and the other cast functions it's not so good.)

You can handle multiple exceptions:
Code:
Try
    mByte = CByte(txtInput.Text)
Catch ex As OverflowException
    MessageBox.Show("That number's too big.")
Catch ex As InvalidCastException
    MessageBox.Show("I don't recognize that as a number.")
End Try
See the documentation, books, etc. for more.

I don't like CodeCruncher's example. I'll get into the specifics later. But first, did you read the article I linked in post #3? It walks through all of the techniques for converting strings to numbers, and ends with the best method.

In my opinion, if you want to take numeric input, you should be using the NumericUpDown control. It already forces the user to type only numbers. You don't have to handle events, validate input, or anything; just use the Value property and be aware you may need to cast it to a different type.

If you really want to use a text box, the best practice is to validate *after* the user typed, not during typing. If you try to validate while they type, you're invariably going to end up in an edge case where you tick your user off. If you wait until they're done, you can be sure you've given them a chance to notice they fat-fingered something. To that end, TryParse() is your best friend. It's explained in detail in my article. Here's what a good snippet would look like:
Code:
If Not Byte.TryParse(txtInput.Text, mByte) Then 
    MessageBox.Show("Your input must be a valid number from 0 to 255.")
    Return
End If
If you really want to validate as the user types like CodeCruncher's example, you shouldn't go as far out of the way. I'm not going to be mean and point out all of the flaws, but there were a few that make me cringe:
  • The Click handler forces the cursor to the end of the number. What if I input 12.34 but realized I wanted 123.4? I'm going to have to backspace several times instead of just clicking where I want to make a correction. But if I use an arrow key it works fine. Inconsistency is infuriating.
  • It uses Val(). Val() is the most insidious crutch from VB6 and one of the few compatibility methods I yell at people for using. I bet you wouldn't expect "123 Mockingbird Ln." to be interpreted as a number. Val() is more than happy to call that 123. Don't use Val(). If you think you need it, hit your thumb with a hammer and ask yourself again. Repeat as necessary. (There's a more detailed rant in my article.)
  • I have no idea what lblFrontArea is for, but I suspect it's being used as a spacer? I'm not familiar with what the * operator does with strings, but I'm suspicious of that line. Anyway, you never set lblFrontArea's text to anything different so why check it with Val() every time?
  • Message boxes are a very user-hostile way to tell someone they typed the wrong value. I'm in the middle of typing some complicated number, then I look up and see that nothing got counted because I hit q instead of 1 at some point and now I have to start over. Don't make your user's life harder.
CodeCruncher, it looks like you have some VB6 experience and are moving to .NET. There's a lot of VB stuff that *works* in .NET, but have better solutions available. I used to know of a couple of MSDN pages with a nice map from VB6 concepts to .NET concepts, but that was lost around the Win7 release; Microsoft only promised to make transition easy for so long. If you want a more detailed critique, let me know and I won't hold back

It's not your fault for getting it wrong. I've seen at least 12 different "good" ways to make a user put numeric input in a text box. Almost all of them are worse than yours; I'd actually not seen an approach like yours yet and there's some redeeming qualities in there if only the techniques weren't a bit haphazard. And you didn't use "On Error Resume Next" so there's hope for you yet Here's a slightly better way to pull it off; it makes use of the ErrorProvider control to tell the user what they did wrong:
Code:
Private Sub txtInput_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtInput.TextChanged
    ValidateNumber()
End Sub

Private Sub txtInput_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles txtInput.KeyPress
    Dim backspace As Char = Chr(8)
    If (e.KeyChar < "0"c OrElse e.KeyChar > "9"c) AndAlso e.KeyChar <> backspace Then
        e.Handled = True
    End If
End Sub

Private Sub ValidateNumber()
    Dim value As Byte
    If Not Byte.TryParse(txtInput.Text, value) Then
        mainErrorProvider.SetError(txtInput, "The value must be a number between 0 and 255 with no decimal points.")
    Else
        mainErrorProvider.SetError(txtInput, "")
    End If
End Sub
No messy mucking about needed. When the user pushes a keyboard button, it ignores anything except digits and backspace (arrow keys are a special case I'd have to go out of my way to ignore; they're allowed.) If a number is allowed through, TextChanged is raised and ValidateNumber() is called. If the value can't be parsed into a Byte, the error provider flashes an icon next to the textbox and provides a tooltip describing what the user can do to fix it. TextChanged is mainly there to address the fact that the user might paste something in from the clipboard and KeyPress can't protect me against that. Most people forget about the clipboard.

I still think it's a bad approach. In my programs, I'd use NumericUpDown.

This *does* let the user enter an invalid number like "1234". A good program assumes its UI validation can be beaten and double-checks the value before using it. For example, if I wanted to tell you if the number was divisible by 2:
Code:
Function IsDivisibleByTwo() As Boolean
    Dim value As Byte
    If Not Byte.TryParse(txtInput.Text, value) Then
        mainErrorProvider.SetError("The value must be...")
        Return False
    End If
    
    Return (value Mod 2 = 0)
End Function
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #8  
Old 05-02-2011, 11:47 PM
CodeCruncher CodeCruncher is offline
Junior Contributor
 
Join Date: Jul 2006
Posts: 355
Default

Quote:
Originally Posted by AtmaWeapon View Post
If you really want to validate as the user types like CodeCruncher's example, you shouldn't go as far out of the way. I'm not going to be mean and point out all of the flaws, but there were a few that make me cringe:
  • The Click handler forces the cursor to the end of the number. What if I input 12.34 but realized I wanted 123.4? I'm going to have to backspace several times instead of just clicking where I want to make a correction. But if I use an arrow key it works fine. Inconsistency is infuriating.
  • It uses Val(). Val() is the most insidious crutch from VB6 and one of the few compatibility methods I yell at people for using. I bet you wouldn't expect "123 Mockingbird Ln." to be interpreted as a number. Val() is more than happy to call that 123. Don't use Val(). If you think you need it, hit your thumb with a hammer and ask yourself again. Repeat as necessary. (There's a more detailed rant in my article.)
  • I have no idea what lblFrontArea is for, but I suspect it's being used as a spacer? I'm not familiar with what the * operator does with strings, but I'm suspicious of that line. Anyway, you never set lblFrontArea's text to anything different so why check it with Val() every time?
  • Message boxes are a very user-hostile way to tell someone they typed the wrong value. I'm in the middle of typing some complicated number, then I look up and see that nothing got counted because I hit q instead of 1 at some point and now I have to start over. Don't make your user's life harder.
CodeCruncher, it looks like you have some VB6 experience and are moving to .NET. There's a lot of VB stuff that *works* in .NET, but have better solutions available. I used to know of a couple of MSDN pages with a nice map from VB6 concepts to .NET concepts, but that was lost around the Win7 release; Microsoft only promised to make transition easy for so long. If you want a more detailed critique, let me know and I won't hold back

It's not your fault for getting it wrong. I've seen at least 12 different "good" ways to make a user put numeric input in a text box. Almost all of them are worse than yours; I'd actually not seen an approach like yours yet and there's some redeeming qualities in there if only the techniques weren't a bit haphazard. And you didn't use "On Error Resume Next" so there's hope for you yet Here's a slightly better way to pull it off; it makes use of the ErrorProvider control to tell the user what they did wrong:
I originally had it coded so the cursor could be placed anywhere in the text box but that compromised the integrity of the data check.
But here is my logic and thinking behind the way I did it...
Let’s say for example I typed the number 123.4 (all which would pass the string test because they are all valid entries) but then I popped the cursor between the 2 and the 3 and put in another period “.” I would now have 12.3.4 which would also pass the string test but not be a valid number for multiplication.
By forcing the cursor to the end it was just a way of making sure a non checked character couldn’t be entered into the text box, the other reason for doing this is by forcing the cursor to the end of the string I only need to evaluate a single / last character every time.
While a period “.” Is a valid entry I can only allow one to be used per number sequence, by starting and the beginning of the string and counting the periods it stops a second one being entered.
Probably seems like a bit of overkill like putting a nail in with a sledge hammer but I like to try making my programs idiot proof (not possible I know but I try), by thinking of every conceivable error someone might enter into the text box.
It annoys me immensely when a programmer allows a wrong value to be entered into a finished product and winds up spitting out an exception error at the user. I would rather catch all their attempts at breaking the system and throw up a message of my own where they can go back and fix the problem (or in this case have it fixed for them) rather than crashing the program.
I probably don’t need to put a message box on every error (personally wouldn’t worry me but could understand that others may not like it) but I figure if your dumb enough to enter a letter into a text box designed for numbers your probably silly enough to need to be told what mistake you made.
For the average Joe who is smart enough to enter the right numbers, they are never going to be penalised by having to see the error message.

Your right about the Val that is just a habit brought over from VB6, I either forgot (terrible memory) or didn’t know it had changed since .net allows me to continue to do it (would need to check other code to see if I have done it differently in the past).
I noticed earlier you did something like “value = CByte(txtInPut.Text)” which I spotted and thought was kind of cool as it looks like you are converting the text into a value but also formatting the text into a Byte type at the same time. Hmmm that looks familiar maybe I have done that before...
If you have seen multiple ways worse than mine then I’m taking that as a compliment
Please if you see a better way (not just different) way of doing things please let me know as I am always ready to learn.
Quote:
Originally Posted by AtmaWeapon View Post
[*]I have no idea what lblFrontArea is for, but I suspect it's being used as a spacer? I'm not familiar with what the * operator does with strings, but I'm suspicious of that line. Anyway, you never set lblFrontArea's text to anything different so why check it with Val() every time?
I presume you’re talking about this bit...
Code:
        If Val(Me.tbCd.Text) <> 0 And Val(Me.lblFrontArea.Text) <> 0 Then
            Me.lblCdA.Text = Me.tbCd.Text * Me.lblFrontArea.Text
        Else
            Me.lblCdA.Text = ""
lol had to look myself there for a second to see why I did that... it was because if lblFrontArea.text was empty “” then I couldn’t do a numeric comparison against 0 without an error. By using Val then “” = 0

I could probably use something like “Me.lblFrontArea.Text is Not Null” or some other non empty check being there is a fair chance lblFrontArea.Text goes through the same Function to check as tbCd.Text.

Thinking back... I think I am comparing against O (zero) because I need it to be a number greater than 0. If I check to make sure it's just not empty and the value is 0 then I am multiplying my number by zero which will throw up an error. Yep that's why I went that way...

Hmmm not sure why I would be comparing < > when frontal area of a vehicle should never be less than 0 sq ft or sq M...

Should check to see if I can get rid of the <, but there must have been a reason for me putting it there... will need to check.

Me.lblCdA.Text = Me.tbCd.Text * Me.lblFrontArea.Text
* is just a symbol for multiplication, how does everyone else do it?
Reply With Quote
  #9  
Old 05-03-2011, 12:13 AM
CodeCruncher CodeCruncher is offline
Junior Contributor
 
Join Date: Jul 2006
Posts: 355
Default

Quote:
Originally Posted by AtmaWeapon View Post
You can handle multiple exceptions:
Code:
Try
    mByte = CByte(txtInput.Text)
Catch ex As OverflowException
    MessageBox.Show("That number's too big.")
Catch ex As InvalidCastException
    MessageBox.Show("I don't recognize that as a number.")
End Try
I like to think of this kind of nested If statement with a safety net... Handy for when you may not get the answer you expect.

In this bit of code I am trying to establish a connnection and send data, there are a number of reasons it may not be sucessful.

There are going to be times where it may not be a user error that causes it to spit out an error, but you want to catch it all the same.

Note: This may not be pretty code or the best way to do it as it is an early attempt the work with sending data.

Thinking back... This may have been someone else sample code that I elaborated on, but this may be a candidtate for AtmaWeapons, multiple exception catch above.

Code:
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click

        Dim tcpClient As New System.Net.Sockets.TcpClient()
        Try
            tcpClient.Connect("127.0.0.1", 8000)
            lblData.Text = vbNewLine + "Connection established with Soliton controller (server)."
            Dim networkStream As NetworkStream = tcpClient.GetStream()
            If networkStream.CanWrite And networkStream.CanRead Then
                ' Do a simple write.
                Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("Is anybody there")
                networkStream.Write(sendBytes, 0, sendBytes.Length)
                ' Read the NetworkStream into a byte buffer.
                Dim bytes(tcpClient.ReceiveBufferSize) As Byte
                networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
                ' Output the data received from the host to the console.
                Dim returndata As String = Encoding.ASCII.GetString(bytes)
                Console.WriteLine(("Host returned: " + returndata))
            Else
                If Not networkStream.CanRead Then
                    Console.WriteLine("cannot not write data to this stream")
                    tcpClient.Close()
                Else
                    If Not networkStream.CanWrite Then
                        Console.WriteLine("cannot read data from this stream")
                        tcpClient.Close()
                    End If
                End If
            End If
            ' pause so user can view the console output
            Console.ReadLine()

        Catch ex As Exception
            Dim bytIPLength As Byte = ex.Message.LastIndexOf(":") - 75
            Dim strIP As String = ex.Message.Substring(75, bytIPLength)
            Dim strPort As String = ex.Message.Remove(0, 76 + bytIPLength)
            lblData.Text = vbNewLine + "No connection could be established with the Soliton controller on IP address " + strIP + " and port number " + strPort _
                         + vbNewLine + vbNewLine + "Please check the following:" _
                         + vbNewLine + "That the port numbers are exactly the same on both the client and the controller." _
                         + vbNewLine + "That the IP addresses are in the same subnet (i.e. both are 255.255.255.255)." _
                         + vbNewLine + "That the IP addresses are NOT the same (i.e. 169.254.0.1 (controller IP) and 169.254.0.2 (client IP)." _
                         + vbNewLine + "The network cable is plugged in securely at both ends (only applicable if client and controller are different devices)."
        End Try

    End Sub
Reply With Quote
  #10  
Old 05-03-2011, 11:16 AM
AtmaWeapon's Avatar
AtmaWeaponBasics Conversion/TryBlock AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

I spent an hour I could have spent playing Minecraft on that post last night. You may not have meant it, but your argument implies you think my points are invalid. I think as a courtesy if you're going to disagree with someone's assessment you should include a reason why you feel like their suggestions shouldn't be taken.

I didn't ask why you did it because it's clear: you needed to make sure your input matched a format and you implemented the best thing you could think of. But if you're going to do explain the "why", it'd be nice to see either, "You're right, your technique is easier and does the same thing." or, "I think your technique works but I had some functional requirements it does not meet." The biggest insult you can give me is to make me feel like you don't read my posts.
Quote:
I originally had it coded so the cursor could be placed anywhere in the text box but that compromised the integrity of the data check.
That's not a problem with your logic, it's a problem with Val(). Val() will tell you that 12a34 is 12. None of the .NET parsing methods I discussed in my article will do that.

If a stool has a broken leg, you shouldn't use it to reach for things on high shelves even if you can stack some books under it to prop it up. It's unstable and dangerous; you should get a new stool. Val() is unsteady and dangerous; use a different stool.

Quote:
Probably seems like a bit of overkill like putting a nail in with a sledge hammer but I like to try making my programs idiot proof (not possible I know but I try), by thinking of every conceivable error someone might enter into the text box.
My technique is just as robust. It's not enough to say "my event handlers will protect me". If you put the validation in the code that gets the values from the controls, you won't have a problem. If you want a full example, ask.
Quote:
For the average Joe who is smart enough to enter the right numbers, they are never going to be penalised by having to see the error message.
I'm going to put my foot down on this one.

If you think your users are "dumb" or need to be penalized then you need to stop writing software until you improve your attitude. No exceptions. It is your obligation as a software developer to do your best to help your users accomplish their goals with as little friction as possible. If you cannot shoulder this burden, you should not make life harder for the rest of us by releasing programs that anger people. Some of us have integrity and want people to respect the job "software developer".

Have you never typed a letter when you meant a number? Do you use the backspace key on your keyboard? Would you like to have someone sit over your shoulder and belittle you every time you make a mistake? If I put a thumbtack on your backspace and delete keys, would you thank me? No? Then why do you think it's a good idea to write programs that do this?

I use a CD image burning program that infurates me every time I use it. When I'm selecting an image, it displays .iso, .bin, and .cue files. Actually, .cue files are an invalid selection; if I pick one I get this dialog:
Quote:
You shouldn't select the CUE file. You should pick the BIN file. I'll fix this mistake for you, but be more careful in the future.
Oh, I'm sorry. I got caught up in the moment. Someone stole my CD collection a few months ago and I was trying to burn an image from the backups I had made. I should have spent a week reading documentation about CD imaging formats first! I'll just shut down my computer and take some days off of work to avoid this sin again.

Or maybe the godforsaken lazy programmer could have hit backspace four times and made a dialog that didn't display CUE files if they were invalid? It took a lot more work to detect it and complain about it than it would have to either silently fix it or just not let me make the mistake. I am never going to donate to this open-source project because of this immature contempt. And the moment I find a free program that does the same thing, I'm never using this one again.

Is that what you want your users to say? "I'm only using this because I have no choice, and I'm not going to pay for it." That's not what I want. I want my users to say, "Why would I use a different program when this one is so useful?"

Quote:
Me.lblCdA.Text = Me.tbCd.Text * Me.lblFrontArea.Text

* is just a symbol for multiplication, how does everyone else do it?
The Text property is a string. It makes no sense to multiply a string. If you had Option Strict on, the compiler would tell you this. (Maybe you've tried it and found it annoying. Ironic since you don't mind bothering your user with message boxes ) Sure, your function won't get there if the strings aren't valid numbers, but the compiler doesn't know that for sure.

The way everyone else does it is they convert strings to numbers before performing math; you don't want the compiler to do magic behind your back because you can't control magic.
Code:
Dim frontArea As Double = Double.Parse(lblFrontArea.Text)
Dim compactDisc As Double = Double.Parse(tbCd.Text)
Dim area As Double = frontArea * compactDisc
lblArea.Text = area.ToString()
Unfortunately your example in #9 is also poor. Luckily it's not touching a nerve like Val() does; this one isn't taught well enough by materials. Developers are strongly urged to not use "catch all" exception handlers. There's plenty of errors you can't reasonably handle. "Catch ex As Exception" has a place in multithreading, but that's a lesson for another day. It's also discouraged to cram as much code as you can in the "Try" part; that makes it harder to figure out what's actually throwing the exception. You're assuming the exception is always the same and has the same message; did you consider that there's at least 6 different exceptions your code can throw and not all of them will include an IP or port number? Here's a more proper approach to handling exceptions in that scenario:
Code:
Dim tcpClient As New TcpClient()
Try
    tcpClient.Connect(...)
Catch ex As SocketException
    Dim message As String = "Could not connect to the Soliton control at port 8000."
    lblData.Text = message
    Return
End Try

' Now the client's connected, let's try to write.
Dim ns As NetworkStream = Nothing
Try
    ns = tcpClient.GetStream()
Catch ex As InvalidOperationException
    lblData.Text = "Lost connection."
    Return
End Try
...
Yes, that's a pain. Tracking down all the exceptions and handling them individually can cause the code explosion. But when a 100,000 line program is chucking errors, it's *really* nice to know exactly which exception you're getting and which line is causing it. "Catch ex As Exception" neuters this effort. The above is just the "unrolled" version of what the code would look like; for such a process I'd end up writing a class and it'd probably look like this:
Code:
Dim connection As New SolitonConnection("localhost", 8000)
If connection.Connect() Then
    Dim response As String = Nothing
    Try
        response = connection.GetResponse("Is anybody there")
    Catch ex As InvalidOperationException
        ReportStatus("Could not get a response from the Soliton controller.")
    End Try

    Console.WriteLine(response)
Else
    ReportStatus("Could not connect to the Soliton controller.")
End If
If you're interested in how I could get from what you've got to that, ask. It's nothing special, just pushing the ugly code behind a pretty facade and translating exceptions to booleans in some cases so I don't have to be thinking about Try/Catch every line. It's a neat topic that deserves a thread of its own.
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #11  
Old 05-03-2011, 01:17 PM
CodeCruncher CodeCruncher is offline
Junior Contributor
 
Join Date: Jul 2006
Posts: 355
Default

Quote:
Originally Posted by AtmaWeapon View Post
I spent an hour I could have spent playing Minecraft on that post last night. You may not have meant it, but your argument implies you think my points are invalid. I think as a courtesy if you're going to disagree with someone's assessment you should include a reason why you feel like their suggestions shouldn't be taken.
My most sincere apologies if my response made you think I wasn’t taking your feedback seriously or giving it due consideration. You made a few points like why was I forcing the cursor to the end, I thought by explaining my reasoning behind why I did it, it might make a little more sense why I went in that direction. I definitely wasn’t trying to justify how my way was better, that thought never crossed my mind.

Also I clearly owe you an apology for not being sufficiently grateful. This is without a doubt a character flaw on my end. I don’t express gratitude very well. I was and am grateful for all assistance.

Quote:
Originally Posted by AtmaWeapon View Post
I didn't ask why you did it because it's clear: you needed to make sure your input matched a format and you implemented the best thing you could think of. But if you're going to do explain the "why", it'd be nice to see either, "You're right, your technique is easier and does the same thing." or, "I think your technique works but I had some functional requirements it does not meet." The biggest insult you can give me is to make me feel like you don't read my posts.
Totally agree, again sorry for my lack of sensitivity.

Quote:
Originally Posted by AtmaWeapon View Post
That's not a problem with your logic, it's a problem with Val(). Val() will tell you that 12a34 is 12. None of the .NET parsing methods I discussed in my article will do that.

If a stool has a broken leg, you shouldn't use it to reach for things on high shelves even if you can stack some books under it to prop it up. It's unstable and dangerous; you should get a new stool. Val() is unsteady and dangerous; use a different stool.
I don’t believe the method I used would allow an “a” to be put in the middle for the Val to produce a wrong result, but your point about not using Val was duly noted and I thought I had expressed a willingness not to use it, but clearly I didn’t articulate that anywhere near clear enough. Sometimes what I feel constitutes acknowledgment is a far cry from what other may rightfully expect.

Quote:
Originally Posted by AtmaWeapon View Post
My technique is just as robust. It's not enough to say "my event handlers will protect me". If you put the validation in the code that gets the values from the controls, you won't have a problem. If you want a full example, ask.
I will endeavour to learn that by reading but if I can’t work it out I would appreciate your assistance.

Quote:
Originally Posted by AtmaWeapon View Post
I'm going to put my foot down on this one.
If you think your users are "dumb" or need to be penalized then you need to stop writing software until you improve your attitude. No exceptions. It is your obligation as a software developer to do your best to help your users accomplish their goals with as little friction as possible. If you cannot shoulder this burden, you should not make life harder for the rest of us by releasing programs that anger people. Some of us have integrity and want people to respect the job "software developer".

Have you never typed a letter when you meant a number? Do you use the backspace key on your keyboard? Would you like to have someone sit over your shoulder and belittle you every time you make a mistake? If I put a thumbtack on your backspace and delete keys, would you thank me? No? Then why do you think it's a good idea to write programs that do this?

I use a CD image burning program that infurates me every time I use it. When I'm selecting an image, it displays .iso, .bin, and .cue files. Actually, .cue files are an invalid selection; if I pick one I get this dialog:

Oh, I'm sorry. I got caught up in the moment. Someone stole my CD collection a few months ago and I was trying to burn an image from the backups I had made. I should have spent a week reading documentation about CD imaging formats first! I'll just shut down my computer and take some days off of work to avoid this sin again.

Or maybe the godforsaken lazy programmer could have hit backspace four times and made a dialog that didn't display CUE files if they were invalid? It took a lot more work to detect it and complain about it than it would have to either silently fix it or just not let me make the mistake. I am never going to donate to this open-source project because of this immature contempt. And the moment I find a free program that does the same thing, I'm never using this one again.

Is that what you want your users to say? "I'm only using this because I have no choice, and I'm not going to pay for it." That's not what I want. I want my users to say, "Why would I use a different program when this one is so useful?"
It is never my intention to belittle anyone or make them feel stupid. I am quite pragmatic by nature and tend to say things without a glossy wrapper, but even so I don’t look down on anyone in a condescending way. I will try to explain if I can a little more about what I meant by the messages.

I have run programs where in the middle of a great application it has crashed in an unrecoverable way, because someone let a bad option get through. I consider myself to be a responsible coder and therefore seek to make it as error proof as possible, ok fool proof and idiot proof are not great descriptions, but the sentiment I was trying to get across was if I put the hard work in other won’t have to be penalised because of my slackness, not that all users are idiots.

Again as far as error messages go I have had the unfortunate experience of trying to use a program that gave very little clues to what sort of data I was supposed to be entering. I would give my right arm for someone to give me an error message that told me exactly what data, or a list of valid characters I should be entering. When I am stuck I am prepared to swallow my pride for help, I realise other won’t, but that doesn’t make either way right or wrong, just how we personally feel about messages.

In my example no one receives a message unless a mistake has been made so is that really superfluous? I’m not justifying my way of doing things but I do believe there are two ways of looking at the same situation.

Firstly while my way might produce error messages as the user goes, if they receive the error message once they are hardly likely to repeat the same error on the next character. The wrong character is also removed saving them effort. I see this as being more efficient as they fix the error once rather than multiple times at the end.

Checking it at the end and popping the messages up one after another (i.e. you enter a letter, you entered two periods, you entered two leading zeros etc) to me would be more annoying, but everyone’s response may be different.

Perhaps the answer is to provide all the error messages at the end in one big message box???

Quote:
Originally Posted by AtmaWeapon View Post
The Text property is a string. It makes no sense to multiply a string. If you had Option Strict on, the compiler would tell you this. (Maybe you've tried it and found it annoying. Ironic since you don't mind bothering your user with message boxes ) Sure, your function won't get there if the strings aren't valid numbers, but the compiler doesn't know that for sure.

The way everyone else does it is they convert strings to numbers before performing math; you don't want the compiler to do magic behind your back because you can't control magic.
Code:
Dim frontArea As Double = Double.Parse(lblFrontArea.Text)
Dim compactDisc As Double = Double.Parse(tbCd.Text)
Dim area As Double = frontArea * compactDisc
lblArea.Text = area.ToString()
Totally agree, my coding has never developed beyond a very fundamental way of taking data from text boxes and representing them as a number for math functions to be performed. I appreciate your suggestions above.
Reply With Quote
  #12  
Old 05-03-2011, 01:19 PM
CodeCruncher CodeCruncher is offline
Junior Contributor
 
Join Date: Jul 2006
Posts: 355
Default

Quote:
Originally Posted by AtmaWeapon View Post

Unfortunately your example in #9 is also poor. Luckily it's not touching a nerve like Val() does; this one isn't taught well enough by materials. Developers are strongly urged to not use "catch all" exception handlers. There's plenty of errors you can't reasonably handle. "Catch ex As Exception" has a place in multithreading, but that's a lesson for another day. It's also discouraged to cram as much code as you can in the "Try" part; that makes it harder to figure out what's actually throwing the exception. You're assuming the exception is always the same and has the same message; did you consider that there's at least 6 different exceptions your code can throw and not all of them will include an IP or port number? Here's a more proper approach to handling exceptions in that scenario:
Code:
Dim tcpClient As New TcpClient()
Try
    tcpClient.Connect(...)
Catch ex As SocketException
    Dim message As String = "Could not connect to the Soliton control at port 8000."
    lblData.Text = message
    Return
End Try

' Now the client's connected, let's try to write.
Dim ns As NetworkStream = Nothing
Try
    ns = tcpClient.GetStream()
Catch ex As InvalidOperationException
    lblData.Text = "Lost connection."
    Return
End Try
...
Yes, that's a pain. Tracking down all the exceptions and handling them individually can cause the code explosion. But when a 100,000 line program is chucking errors, it's *really* nice to know exactly which exception you're getting and which line is causing it. "Catch ex As Exception" neuters this effort. The above is just the "unrolled" version of what the code would look like; for such a process I'd end up writing a class and it'd probably look like this:
Code:
Dim connection As New SolitonConnection("localhost", 8000)
If connection.Connect() Then
    Dim response As String = Nothing
    Try
        response = connection.GetResponse("Is anybody there")
    Catch ex As InvalidOperationException
        ReportStatus("Could not get a response from the Soliton controller.")
    End Try

    Console.WriteLine(response)
Else
    ReportStatus("Could not connect to the Soliton controller.")
End If
If you're interested in how I could get from what you've got to that, ask. It's nothing special, just pushing the ugly code behind a pretty facade and translating exceptions to booleans in some cases so I don't have to be thinking about Try/Catch every line. It's a neat topic that deserves a thread of its own.
As above (#9) it came back to me (poor memory) that much of that was not my code, but someone else’s I tweaked because the message didn’t encompass many of the things that might be wrong.

I still have lots to learn about moving data between PCs and do need to one day finish off this program, so I do and would appreciate any improvements you can suggest as I had difficulty finding even a basic bit of code that told me how to establish the connection.

Again I sincerely apologise for not recognising your contributions, they were most definitely appreciated even if my pragmatic way didn’t reflect that.
Reply With Quote
  #13  
Old 05-03-2011, 03:57 PM
NewVBProgrammer NewVBProgrammer is offline
Centurion
 
Join Date: Jul 2010
Location: Grand Manan
Posts: 163
Default

Quote:
Originally Posted by AtmaWeapon View Post
In my opinion, if you want to take numeric input, you should be using the NumericUpDown control. It already forces the user to type only numbers. You don't have to handle events, validate input, or anything; just use the Value property and be aware you may need to cast it to a different type.
I didn't even know that control existed. I've just implemented it now. Makes that task a lot easier, but, I'm going to play around with this too..

Quote:
Code:
If Not Byte.TryParse(txtInput.Text, mByte) Then 
    MessageBox.Show("Your input must be a valid number from 0 to 255.")
    Return
End If
Reply With Quote
  #14  
Old 05-03-2011, 04:02 PM
AtmaWeapon's Avatar
AtmaWeaponBasics Conversion/TryBlock AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

I've got thick skin, don't worry about me staying mad. But I do complain when I feel like the skin is getting poked.

I think the best way to make my point is to show you what I think a good application should look like. I'm not sure if you're using VS 2010 or not, so I'm going to attach a .vb file that should work in everything down to VS 2005. Just add the form to the project in place of Form1.vb and it ought to work. Since I had to use one file, I add the controls by hand; you can ignore the last 100 or so lines of the file conveniently marked "ignore this".

The application calculates the area of a rectangle on the fly as users change the values. Width input is via a NumericUpDown to demonstrate that control. Height input is via a TextBox that will complain if you do something invalid. Just to make things difficult, "valid" means "numbers between 500 and 10,000". There's also a button that is disabled if input is not valid.

The NumericUpDown for width requires no validation at all. (I did find something bad out about it and I might loosen my stance. We'll discuss that later.) It only allows numeric values to be entered, and I used the Minimum and Maximum properties to restrict it to between 500 and 10,000. There's no chance of overflow because of this so it's safe to cast Value from Decimal to Double. Each time the text value changes (that event is actually hidden!) I call CalculateArea() to update the area.

The TextBox for height requires more attention. I opted to not try and restrict non-numeric values. Instead, I call CalculateArea() each time the text changes because I know nothing bad can happen if the text is invalid.

CalculateArea() starts by getting the width from the NumericUpDown. Next, it uses the helper method ValidateHeight() to determine if the height is valid; if not it displays an error string for the area and quits. If the height is valid, the area is calculated and displayed.

ValidateHeight works sort of like a TryParse() method. It returns True and sets the ByRef parameter height if the text box has a valid height; otherwise it returns false. First, the number is checked for validity; if it's not valid an error message is set and False is returned. Next, the number is checked to make sure it's bigger than 500; if not an error message is displayed and False is returned. Likewise for "smaller than 10,000". If the number is valid, bigger than 500, and smaller than 10,000, the error message is cleared and True is returned.

There is no way to crash the program via text input. The NumericUpDown won't have anything that isn't a digit. The text box is fine with accepting that input, but nothing invalid can pass through ValidateHeight() to get to the math part. I don't have to pester the user with focus-breaking message boxes because the error provider lets me show a convenient indicator that lets them finish. Imagine how hard it would be to enter "500" in the text box if at "5" and "50" you got a message box warning you it was invalid! It'd be especially difficult if I were resetting the text at each mistake. One false step trying to go from "10000" to "1000" and you have to start over at 500. It ends up creating a kind of puzzle where if the user wants to input a new number they have to first figure out a series of steps that will minimize message boxes. Try imagining how to get from "750" to "751" without a message box. It's impossible if you're erasing errors.

One thing I noticed: the NumericUpDown is actually pretty horrible if you want to type out a number. It does the same silly text reset behavior, and it's a major pain. It's apparently only good if you can get close to the number then use the arrow keys. That's a real shame. But it's also a testament to how easy it is to make something useless when you're trying to help. It's best to let the user type whatever and tell them what's wrong when it's wrong. They want the result, so they'll fix the problem. The more you chain them up, the less they can do.

(Incidentally, there's some cases where letting them use a wrong value might be valid. That's a fun story, but off-topic.)
Attached Files
File Type: vb Form1.vb (4.8 KB, 3 views)
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #15  
Old 05-03-2011, 04:02 PM
NewVBProgrammer NewVBProgrammer is offline
Centurion
 
Join Date: Jul 2010
Location: Grand Manan
Posts: 163
Default

Quote:
If Not Byte.TryParse(txtInput.Text, mByte) Then
in the second argument what is that all about? what is mByte, and are there other examples of what can be done witht he TryParse method?
Reply With Quote
  #16  
Old 05-03-2011, 04:14 PM
NewVBProgrammer NewVBProgrammer is offline
Centurion
 
Join Date: Jul 2010
Location: Grand Manan
Posts: 163
Default

Code:
_err.SetError
what's this?
Reply With Quote
  #17  
Old 05-03-2011, 04:28 PM
NewVBProgrammer NewVBProgrammer is offline
Centurion
 
Join Date: Jul 2010
Location: Grand Manan
Posts: 163
Default

How do I go about trying your other example. This clearly isn't right..

Code:
Public Class Form1
    Dim myByte As Byte

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        myByte = TextBox1.Text

        If Not Byte.TryParse(TextBox1.Text, myByte) Then
            MessageBox.Show("Your input must be a valid number from 0 to 255.")
            Return
        End If

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


    End Sub
End Class
Reply With Quote
  #18  
Old 05-03-2011, 04:30 PM
NewVBProgrammer NewVBProgrammer is offline
Centurion
 
Join Date: Jul 2010
Location: Grand Manan
Posts: 163
Default

never mind, I figure it out, lol..it goes in the texbox... how does that code know to run in the text box...does that sub run at all times?
Reply With Quote
  #19  
Old 05-03-2011, 04:36 PM
piggybank1974's Avatar
piggybank1974 piggybank1974 is offline
Ultimate Contributor
 
Join Date: Mar 2002
Location: weston-super-mare(UK)
Posts: 1,795
Default

it should be more like this:

Code:
Public Class Form1 Private myByte As Byte Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click If Byte.TryParse(TextBox1.Text, myByte) = false Then MessageBox.Show("Your input must be a valid number from 0 to 255.") Exit Sub End If End Sub End Class
Reply With Quote
  #20  
Old 05-03-2011, 04:48 PM
NewVBProgrammer NewVBProgrammer is offline
Centurion
 
Join Date: Jul 2010
Location: Grand Manan
Posts: 163
Default

I've remade the app, still trying to figure out these basic things...the program catches a few errors, but it's still buggy.

Code:
Option Strict On
Public Class Form1
    Dim myByte As Byte

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Try
            myByte = CByte(TextBox1.Text)
        Catch ex As OverflowException
            RichTextBox1.Text = "the number value you have entered cannot be correctly stored in to the Byte" & _
                "DataType. Byte ranges from 0-255. Please try a value within that range for conversion."
        End Try


        Dim integer1 As Integer

        integer1 = CInt(myByte)

        RichTextBox1.Text = "this is the conversion of your byte to an ingetger: " & integer1


    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


    End Sub

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged

        If Not Byte.TryParse(TextBox1.Text, myByte) Then
            MessageBox.Show("Your input must be a valid number from 0 to 255.")
            RichTextBox1.Text = "You have succesfully entered an invalid key to represent a byte. Which is a number."
            Return
        End If



    End Sub
End Class

When I enter a number too big to be a Byte I get this in my rich text box, haha.

"this is the conversion of your byte to an ingetger: 0"
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump

Advertisement:





Free Publications
The ASP.NET 2.0 Anthology
101 Essential Tips, Tricks & Hacks - Free 156 Page Preview. Learn the most practical features and best approaches for ASP.NET.
subscribe
Programmers Heaven C# School Book -Free 338 Page eBook
The Programmers Heaven C# School book covers the .NET framework and the C# language.
subscribe
Build Your Own ASP.NET 3.5 Web Site Using C# & VB, 3rd Edition - Free 219 Page Preview!
This comprehensive step-by-step guide will help get your database-driven ASP.NET web site up and running in no time..
subscribe
Basics Conversion/TryBlock
Basics Conversion/TryBlock
Basics Conversion/TryBlock Basics Conversion/TryBlock
Basics Conversion/TryBlock
Basics Conversion/TryBlock
Basics Conversion/TryBlock Basics Conversion/TryBlock Basics Conversion/TryBlock Basics Conversion/TryBlock Basics Conversion/TryBlock Basics Conversion/TryBlock Basics Conversion/TryBlock
Basics Conversion/TryBlock
Basics Conversion/TryBlock
 
Basics Conversion/TryBlock
Basics Conversion/TryBlock
 
-->