How do I use Do Until with a previous Try Catch Exception to avoid running the code twice - vb.net

i have this line of code to catch an exception if a letter is inputed, or if it is out of rang as a number, but I have added WHEN to avoid catching numberical data. Now how can I use an exception error to use it before my case statement in order to avoid running the code twice, cause once the case codes has been through it will run a clear txtbox which is already taken care by the try catch, don`t if thats clear for you but i understand it. here is the code in parts...
Try
'Integer Levels: intLvls is egual to the assigned text box, the first one from
'the top, this line of code allow the user input to be captured into a variable.
intLvls = txtBoxLvl.Text
Catch ex As Exception When IsNumeric(intLvls)
ErrTypeLetterFeild1()
Finally
analysingvalues1()
End Try
WHAT I WOULD LIKE TO DO: Use loop until refencing the exception error to avoid running this following part of the code:
Private Sub analysingvalues1()
Do Until IsNumeric (ex As Exception)<------how do i do this???
Loop
the case part of the code:
Select Case intLvls
'User is prompt with the following label: lblLvl "Level of salespersons 1 - 4"
'to make a choice from 1 to 4 as available values.
Case 1 To 4
'This line regulates the range of acceptable values, first textbox: must be egual
'or higher than 1 and lower or egual to 4. Upon such rules a validation becomes
'correct and is directed to the isValidCalculation sub.
isValidCalculation()
Case Is < 1
ErrType1NumberRangeFeild()
Case Is > 4
ErrType1NumberRangeFeild()
Case Else
If txtBoxLvl.Text = "" Then
ErrTypeClear1()
Else
If Not IsNumeric(txtBoxLvl.Text) Then
ErrType1NumberRangeFeild()
Else
ErrTypeLetterFeild1()
ErrTypeClear1()
End If
End If
End Select 'Ending choices.
End Sub
Tks for your help!

If you turn on Option Strict this:
intLvls = txtBoxLvl.Text
Will no longer compile. This should tell you that your doing something smelly.
Turn on Option Strict
The correct solution is not to blindly allow the runtime to cast string to int for you, and catch the exceptions.
When you are converting string user input to an integer, bad input is not an exceptional condition, it is something you should expect and code defensively for.
I would rewrite it to something like this:
'Integer Levels: intLvls is egual to the assigned text box, the first one from
'the top, this line of code allow the user input to be captured into a variable.
if integer.TryParse( txtBoxLvl.Text, intLvls )
analysingvalues1()
else
ErrTypeLetterFeild1()
Edit - As pointed out by Chris below, I meant Option Strict. I recommend using but Explicit and Strict, and Infer if available.

Related

Excel VBA Match if value is null

I have a piece of code within a larger script that simply allocates a value to "i" based on a match. The idea being I want it to give the match value if the value entered is found, or 0 if not. If it's 0, I can then exit sub with a message to the user. However, any time the match finds a null value, it just kills the sub, instead of it being handled as part of the iferror I've introduced. I've tried various manners of checking (using iif(iserror) for example) but none seem to work.
Code causing the issue is below:
i = Application.WorksheetFunction.IfError(Application.WorksheetFunction.Match(username, EL.Range("A:A"), 0), 0)
i is dim as an integer
Username is dim as a string, and comes from an inputbox
EL is dim as a worksheet, and contains the correct info.
This has absolutely no issues if I introduce any name that exists, it only fails as soon as I input a name that does not work, and I'm sort of stumped as to why. I see no reason for it to fail, but feel like I'm missing something simply and in-my-face.
Use this instead. Using Application instead of WorksheetFunction enables the error to be trapped and tested.
i = Application.IfError(Application.Match(UserName, EL.Range("A:A"), 0), 0)
I would use a slightly different approach to trap an error on Application.Match function:
Dim i As Variant
i = Application.Match(UserName, EL.Range("A:A"), 0)
' if Match wasn't able to found a "match"
If IsError(i) Then i = 0

why would a boolean revert to an original value?

I know this might be a more of a general question, but I've looked at my code a 100 times and am not sure what's wrong. I set a global flag so that it can be used in different forms of my application.
Dim OverPopulated as Boolean
I have a function where I first set it to FALSE, and after it goes through some validating it gets set to TRUE.
Now i do a bunch of stuff, go through different forms, and the value stays correct the entire time. Basically I need this value for another form, so when I check
if OverPopulated = false then
MsgBox "You Can't do this and that"
exit sub
End if
Then all of the sudden it gets set to FALSE. I've went through every instance of OVERPOPULATED in my application and put a break point to it to make sure that nowhere do i set it to FALSE, except for the one time I set it to FALSE before my validation.
I only have it in 2 other forms in my applications. There is one place where the flag is being run twice through the same statement (just like the one above). The first time it goes through, the value is correct, then it goes through again and the value is set to FALSE.
Any ideas? if this is too vague, please let me know, I'll try to edit it.
EDIT: I deleted a lot of the code but here's how it looks.....
Dim OverPopulated as Boolean
' modular level
Private Sub ValidatePopulation()
Dim admDate as date
OverPopulated = False
admDate = Format(Now(), "mm/dd/yyyy")
Select Case revPURP
Case 0, 1, 2
'Check make sure these fields
'some if statements, checking, validation
Case Else ' no need to do a
End Select
OverPopulated = True 'I MAKE SURE IT GETS HERE and is set to TRUE!!!
End sub
Now, in other functions I used it like this...
If OverPopulated = False Then
If optStat (0).Value = True Or optStat (1).Value = True Then
MsgBox "You are not able to do this”, vbCritical, "Incorrect review status...."
TabPop.Tab = 6
End If
Exit sub
Else
'Proceed with SAVE
End If
So I have this. and I have another statement just like this somewhere else. This one gets hit twice. The first time I go through it line by line and it's FALSE, then the 2nd time around the value is TRUE.
It looks like for some reason the value was getting reset to FALSE. I took out the Dim OverPopulated as Boolean from my form code, and placed it in a GLOBAL module where all the other globals are stored. This seems to have fixed the issue of the value remaining the same while I'm manuevering in the application. Thank you for all your comments.
Global OverPopulated as Boolean

Try-Catch exception handler VB.NET

I'm working through a Hair Salon application in VB.NET. Basically the user is able to select the stylist, service(s), age category and enter the number of visits. I then have a Calculate button in order to calculate the total price. I'm required to use Try-Catch for exception handling but I'm not too familiar with it. I'm assuming it's used for error handling, in which case how would I check to see if client visits is greater than 0 and to check to see if the value entered is an integer? Here is what I've tried with the client visits:
Try
(intClientVists > 0)
Exit Try
Catch ex As Exception When
(intClientVists < 0)
Exit Try
End Try
Just hoping someone can steer me in the right direction because I'm not really sure what I'm doing for this particular aspect of the application. Thanks.
Yes, Try/Catch blocks are used for error handling. However, they're not really for this kind of error. Try/Catch blocks are more for errors made by the programmer or the computer (could not allocate memory, could not connect to database, could not open a file, tried to divide by zero, could not cast a value to the specified type) than for errors made by the user (entered a wrong number).
Instead, you want a simple If/Else block:
If intClientVists > 0 Then
'Do something
Else
'Do something else
End If
If you really want to use exception handling for this (again: not normally the best choice), here is how it might look:
Try
If intClientVists < 0 Then Throw New InvalidOperationException()
'Data is OK. Continue processing here
Catch Ex As InvalidOperationException When intClientVisits = 0
'Show one error message
Catch Ex As InvalidOperationException When intClientVisits < 0
'Show different error message
End Try
This MSDN article gives you a list of .NET exceptions that you can use in a Try-Catch. These are actual errors as opposed to input validation checking, like Joel explained.
Basically, you put some logic in the Try block, and if you want to do something in the case of a specific exception, then you catch that exception type and put your logic in that Catch block. Then as a "catch-all" just simply catch "Exception" to do something no matter what type the exception is.
In your particular case, it sounds like the most likely use of a Try-Catch would be if the user inputs the number of visits into a regular text box in which they could enter letters. Here is an example of what you could do for that:
Try
If CInt(txtNumVisits.Text) > 0 Then
'logic here
End If
Catch ex As Exception
'If user entered something other than an integer in that box then an InvalidCastException will be caught
'enter logic here for if that's the case. For example:
MessageBox.Show(Me, "Please enter a number >= 0", "Invalid Input")
txtNumVisits.Focus()
End Try

What are a good No OP operation for vb.net?

Something we can just put break point on while making sure it doesn't do anything else.
In c, that would be while(false);
What to do in vb.net?
If you always need it to break there you can put
Stop or Debugger.Break()
If you really want a No-Op for some reason (could this turn into a contest for the most ineffectual single line of code?!), how about these?
System.Threading.Thread.Sleep(1) - 1ms is unlikely to have a huge impact outside of a loop
Debug.Write("") - doesn't appear to output anything.
There is a legitimate use-case for this.
When a temporary breakpoint is required after the statement of interest and this is the last line inside an if statement, an extra no-op type statement is required to place the temporary breakpoint on.
In this case I use:
If someCondition >0 Then
doSomething
Space (1) 'Dummy line to place breakpoint
End If
This returns a string containing one space, but does not assign it to anything. I use it in VBA, but it's also supported in .net
My two cents...
You can combine any series of commands onto one line with colons:
If False Then : End If
Select Case False : Case Else : End Select
I've also made it into a sub. Then it gets a recognizable name of own:
'Definition...
Public Sub noop () 'Or Private, Protected, etc.
End Sub
'Usage...
Sub Main()
If sometest Then
noop
Else
MsgBox "test is false"
End If
End Sub
Very strange question, you could place a BreakPoint about anywhere in the code. But here are some useless lines :
Do While False
Loop
While False
End While
Even the following :
Dim hello = Nothing
Or this :
Format("", "")
A no-op statement is also useful as an aid to document code nicely and make it more easily understandable. You could for example put in a statement like A = A.
For example:
If MyNumber => 100 then A = A
Else:
I know this is an old query, but for what it is worth, my preferred solution to the original question is
Debug.Assert (vbTrue)
If you wanted, you could use a variable instead of vbTrue and then enable/disable all breakpoints in your code by changing one variable
Dim bDisableBreakpoints as Boolean: bDisableBreakpoints = vbTrue
'your code here
Debug.Assert (bDisableBreakpoints)
'rest of your code
Simply change bDisableBreakpoints to vbFalse and the breakpoints will be set wherever you have used Debug.Assert
My personal favorite is
dim b=1
Then I put a breakpoint there.

Object reference not set to an instance of an object (Completely broken?) in vb.net

I know, I know, I could have used a for loop, dont tell me anything about that. Please, help!
Private Function LoadSaved() ''//Loads saved clippings if the user wants us to
Dim ZomgSavedClips As StringCollection
If IsDBNull(My.Settings.SavedClips) = False Then ''//If it is null this would return a rather ugly error. Dont want that do we?
ZomgSavedClips = My.Settings.SavedClips ''//ZomgSavedClips name was a joke, I just felt like it.
ZomgSavedClips.Add(" ") ''//This line ought to fix the error, but doesnt
i = 0
While i < ZomgSavedClips.Count ''//This is where the error occurs
ClipListings.Rows.Add(ZomgSavedClips(i))
i = i + 1 ''//First time I wrote this function I forgot this line. Crashed mah comp. Fail.
End While
End If
End Function
The line While i < ZomgSavedClips.Count is bugging, I know that the .count should return null but I even added a blank piece of text just to stop that. Whats up with this? Should I add actual text?
SavedClips is null no? If it is null it could pass the test IsDBNull beacuse the both are not the same
Obviously, My.Settings.SavedClips is still set to Nothing.
SavedClips is regular 'ole null (nothing in VB). Include a check for "My.Settings.SavedClips is nothing". If that evaluates to true then just leave the function.
I even added a blank piece of text just to stop that.
All you did was move where the error happens. You can't call .Add() on a null/Nothing object.
'''<summary>Loads saved clippings if the user wants us to</summary>'
Private Sub LoadSaved() ''//Loads saved clippings if the user wants us to
''//Load saved clips into memory
Dim ZomgSavedClips As StringCollection = My.Settings.SavedClips
If ZomgSavedClips Is Nothing Then ZomgSavedClips = New StringCollection()
''//Apply loaded clips to visible listings
Dim i As Integer
While i < ZomgSavedClips.Count ''
ClipListings.Rows.Add(ZomgSavedClips(i))
i += 1
End While
End Sub
Some notes on this code:
Don't use Function when you mean Sub
Since you'll be selling this code to others, you want to use xml comments at the top so that Visual Studio can give better intellisense helps.
IsDBNull() doesn't do what you think it does.
Yes, you should use a for loop, but since you already commented on that I left the while loop alone with the assumption that there's more code you didn't show us.