errors after turning on option strict

bones

Well-known member
Joined
Aug 23, 2014
Messages
143
Programming Experience
Beginner
This all worked until today when I turned on the option "strict" in the debugger.

I'm simply taking the text from a radio button on the form and entering it into the last column of the DGV. It's used as an identifier for that particular row's data source values.


I had to add the ".ToString" to get the blue line to go away in the code editor.


VB.NET:
For Each r As DataGridViewRow In DataGridView1.Rows
            If r.IsNewRow Then Continue For


            Dataanalysis.DGV1.Rows.Add({r.Cells(0).Value, r.Cells(1).Value, r.Cells(2).Value, r.Cells(3).Value})
           
            Select Case True
                Case Me.RBtnPort1.Checked
                    If r.Cells(10).Value.ToString = ("") Then[B]***BLOWS UP RIGHT HERE*** [[/B]Error Message:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
                        r.Cells(10).Value = Me.RBtnPort1.Text
                    End If
               
There are 5 more cases below this but they all do the same thing...just use .text from a different button.

Another issue and I have a bunch just like this that are now broken...

VB.NET:
Private Sub DataGridView1_CellValidated(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV1.CellValidated


        Dim vdiam = Val(Me.TextBox1.Text) ' Valve Diameter
        Dim factor = vdiam * 3.14 ' the Cd Calculation
        Dim count = Val(Me.TextBox7.Text) ' Number of valves


        For Each r As DataGridViewRow In Me.DGV1.Rows
            'Valve Coefficient formula = cfm / ((valve diameter * 3.14 * lift)*146) * number of valves
            r.Cells(5).Value = CDbl(r.Cells(2).Value.ToString) / ((factor * CDbl(r.Cells(0).Value.ToString)) * 146) / count BLOWS UP ON THIS LINE....

The letter N in count has a red underline and the error is Object reference not set to an instance of an object.
 
Last edited:
Did you actually read the error message? It's telling you that that line is using an index that's out of range. There's only one index being used on that line so there's only one place the error could be.
 
Did you actually read the error message? It's telling you that that line is using an index that's out of range. There's only one index being used on that line so there's only one place the error could be.

Ha..you seem to forget how GREEN I am as this... I honestly don't know... could you point me to it?

Regarding the first error...I think I have that fixed because now when I click the capture button that error no longer shows up....but the second posted error still does...
 
Oh wait... I thought I posted the second error as well..but I don't see it... I had edited that original post.. I will post second error for you to look at... there are a bunch of formulas I will have to fix...
 
Ok... to be clear for you now...

I believe I have the original error fixed. Pleas assist with this one...

VB.NET:
Private Sub DataGridView1_CellValidated(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV1.CellValidated


        Dim vdiam = Val(Me.TextBox1.Text) ' Valve Diameter
        Dim factor = vdiam * 3.14 ' the Cd Calculation
        Dim count = Val(Me.TextBox7.Text) ' Number of valves


        For Each r As DataGridViewRow In Me.DGV1.Rows
            'Valve Coefficient formula = cfm / ((valve diameter * 3.14 * lift)*146) * number of valves
            r.Cells(5).Value = CDbl(r.Cells(2).Value.ToString) / ((factor * CDbl(r.Cells(0).Value.ToString)) * 146) / count BLOWS UP HERE

The letter "n" in count is underlined in red... the error message is Object reference not set to an instance of an object.



Curiously... after turning on STRICT.... I went through an used the intelisense suggestions to fix things... No errors showed until I debugged it again...now new errors are cropping up. That said, I question the intellisense ability to suggest correct code...... arrrrghh..
 
Ok... to be clear for you now...

I believe I have the original error fixed. Pleas assist with this one...

VB.NET:
Private Sub DataGridView1_CellValidated(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV1.CellValidated


        Dim vdiam = Val(Me.TextBox1.Text) ' Valve Diameter
        Dim factor = vdiam * 3.14 ' the Cd Calculation
        Dim count = Val(Me.TextBox7.Text) ' Number of valves


        For Each r As DataGridViewRow In Me.DGV1.Rows
            'Valve Coefficient formula = cfm / ((valve diameter * 3.14 * lift)*146) * number of valves
            r.Cells(5).Value = CDbl(r.Cells(2).Value.ToString) / ((factor * CDbl(r.Cells(0).Value.ToString)) * 146) / count BLOWS UP HERE

The letter "n" in count is underlined in red... the error message is Object reference not set to an instance of an object.



Curiously... after turning on STRICT.... I went through an used the intelisense suggestions to fix things... No errors showed until I debugged it again...now new errors are cropping up. That said, I question the intellisense ability to suggest correct code...... arrrrghh..

There is no `count` on the line you mentioned. Even if there was, it's not going to cause the issue you mention on that line. A NullReferenceException occurs when you try to access a member of on object that doesn't exist. My guess is that you are encountering an empty cell. If the Value of a cell is Nothing then there's no object to call ToString on. If cells might be empty then it's up to you to test for that and only use them if they contain data.
 
There is no `count` on the line you mentioned. Even if there was, it's not going to cause the issue you mention on that line. A NullReferenceException occurs when you try to access a member of on object that doesn't exist. My guess is that you are encountering an empty cell. If the Value of a cell is Nothing then there's no object to call ToString on. If cells might be empty then it's up to you to test for that and only use them if they contain data.

That is exactly what's happening. I realized that when I sat down here this morning. I need some advice..

On my dataanalisys form I have a DGV and text boxes. The values in the text boxes are used in formulas in the DGV. They are null by default. I thought perhaps setting a default value of 0 might resolve the problem so I just did that and went to run debug. Now I'm getting this message and the main form won't open. The dataanalysis for is NOT the main form...so I'm lost as to what's wrong now. I can't decipher those cryptic error messages very well ....just yet... Now I have to dive into this.

MY GRIPE WITH OPTION STRICT VS COMMON SENSE VS MICROSOFT HAVING ANY OF THE LATTER...

After reading up on Option Strict I see it's usefulness...HOWEVER IF IT'S SO F'NG IMPORTANT AND WONDERFUL IT SHOULD BE TURNED ON BY DEFAULT...so that when a new programmer sits down to work on their first application they don't have a few thousand lines of working code that suddenly gets broken........ SEEMS LIKE A NO BRAINER TO ME...BUT HEY... I THINK DIFFERENTLY THAN MICROSTUPID.... I liken this to a scenario of...... There's a trail in the woods that leads to a 1000 foot cliff. It's covered in fog. There's an LED warning sign about the cliff being there....but the hiker needs to know it's there and also where the switch is to turn it on......... WTF... A situation born out of typical corporate lack of communication between departments perhaps? Or just plain stupidity.... I lean toward the latter on the part of whoever released this version of VB2010 without the insight to set option strict as the default setting.....I'm so pissed I could spit bullets this morning....

System.InvalidOperationException was unhandled
HResult=-2146233079
Message=An error occurred creating the form. See Exception.InnerException for details. The error is: Object reference not set to an instance of an object.
Source=QuickStart Communicator
StackTrace:
 
Last edited:
Object reference not set to an instance of an object.
As explained .Value.ToString is what throws null reference exception, when Value is Nothing (null) there is no object to call .ToString on. On that case, why would you convert something in a numeric expression to String? Get rid of those ToString calls.
I have also explained in other thread of yours that Value property is type Object (it can return any type of value), so to use it in a numeric expression you have to convert it to a relevant numeric data type, check out the data types and the conversion functions available:
Data Type Summary (Visual Basic)
Conversion Summary (Visual Basic)
whoever released this version of VB2010 without the insight to set option strict as the default setting
VB has always been like that, and may be so forever. VB is supposed to the easiest programming language for a beginner to start with, and that by default allows the entire type system to be hidden for the novice. Me and many others think this is a disadvantage. IDE/Intellisense has gotten a lot better over the years both in code completion and in helping correct beginner type/conversion mistakes, and Option Infer that was introduced a few years back also helps in writing good type safe code fast without having to explicitly know/write the type everywhere in code (and you can learn from type inference too). I think with just a basic understanding of data types and object types a beginner will with help of IDE/Intellisense and Option Strict+Infer: (a) write better code, (b) write code faster, and (c) advance in programming faster. Problems in coding may also appear more explicit and at compile-time rather than run-time, which can lead to solving the problem faster.
 
As explained .Value.ToString is what throws null reference exception, when Value is Nothing (null) there is no object to call .ToString on. On that case, why would you convert something in a numeric expression to String? Get rid of those ToString calls.
I have also explained in other thread of yours that Value property is type Object (it can return any type of value), so to use it in a numeric expression you have to convert it to a relevant numeric data type, check out the data types and the conversion functions available:
Data Type Summary (Visual Basic)
Conversion Summary (Visual Basic)

VB has always been like that, and may be so forever. VB is supposed to the easiest programming language for a beginner to start with, and that by default allows the entire type system to be hidden for the novice. Me and many others think this is a disadvantage. IDE/Intellisense has gotten a lot better over the years both in code completion and in helping correct beginner type/conversion mistakes, and Option Infer that was introduced a few years back also helps in writing good type safe code fast without having to explicitly know/write the type everywhere in code (and you can learn from type inference too). I think with just a basic understanding of data types and object types a beginner will with help of IDE/Intellisense and Option Strict+Infer: (a) write better code, (b) write code faster, and (c) advance in programming faster. Problems in coding may also appear more explicit and at compile-time rather than run-time, which can lead to solving the problem faster.

When I turned on option strict at your suggestion, I had over 100 lines of broken code. Intellisense offered fixes to the code for some things and not for other things. That particular part where I added .ToString was previously [Value =] and that was among the many similar lines that intellisense offered no fix for....so I had to fiddle with code until the blue squiggly lines went away. To me, when the line goes away I assume the code is valid....OBVIOUSLY THAT IS A WRONG ASSUMPTION...

According to MS....option strict came along with Visual Basic dot net 2005... was not part of vb6.

I respect your input on the features being helpful in the ways you suggest. I stand by my view that if that option is beneficial...it should be on by default... It would prevent situations like this.
 
Last edited:
Anyway.... At this point I can't even open a form... What's wrong with this code??

VB.NET:
Private Sub Chart1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Chart1.Click
        'Show the Data Analysis Form
        Dataanalysis.ShowDialog()

Object reference not set to an instance of an object. is the error message.

Considering I can open other forms that have formanme.showdialog() as the code....I'm puzzled at why this is broken. Could it be something in the dataanalysis form load event causing this error... The form won't load..
 
I found this information when searching for other opinions on option strict. Those that support it agree with me that it should have been turned on by default....

Regardless, it buys you things but at the cost of other things... late binding for example. Something I have NO CLUE about how to address when that error now comes up in my code... I found this as well.

What I'm interested in knowing about is the ability to have option strict on by default but turn it off on a case by case basis to allow for late binding that becomes a problem when it's on.. I have to wade through a significant number of issues now and believe turning off option strict in sections of code that have late binding issues would be helpful while I sort out the other problems... How do you go about turning if off for a section of code?

I tend to agree that this probably shouldn't be off by default, but it's nowhere near as poisonous as Option Explicit. Option Explicit Off has no legitimate use. Option Strict Off has one clear use case: it's great when you're writing a lot of late binding code. Let the IL deal with all the nasty, verbose type conversions. As Scott points out, we can now usepartial classes in VB.NET 2.0 to mark selected sections of code Option Strict Offwhile leaving the rest Option Strict On. It's the best of both worlds.


 
Those that support it agree with me that it should have been turned on by default....
Yes, I think it should. MS strongly thinks otherwise, they didn't put that option default there at a whim. I will continue to recommend anyone posting non-strict code here to turn it on, because I strongly thinks that it at longer term will be more helpful to them.
Regardless, it buys you things but at the cost of other things... late binding for example.
You're not writing any code that requires late binding :) That is mostly for interacting with old COM automation servers, and even then a type library is usually available, though you often have to type cast a lot.
The cost is a little slower start when learning to write good code to begin with, instead of starting out with limited understanding and bad habits and later trying to fix the problem code that produced, that cost is as I see it much higher.
 
Yes, I think it should. MS strongly thinks otherwise, they didn't put that option default there at a whim. I will continue to recommend anyone posting non-strict code here to turn it on, because I strongly thinks that it at longer term will be more helpful to them.

You're not writing any code that requires late binding :) That is mostly for interacting with old COM automation servers, and even then a type library is usually available, though you often have to type cast a lot.
The cost is a little slower start when learning to write good code to being with, instead of starting out with limited understanding and bad habits and later trying to fix the problem code that produced, that cost is as I see it much higher.


:cocksure: I got things working again....WHEW! ...what an unexpected treat this has been..... LOL

Please explain to me why the code to open the datanalysis form broke? I don't understand how that happened.

Is this the way I should be opening all forms? I added that first line today in effort to overcome the issues I was having.

VB.NET:
Dim dataanalysis As New DataAnalysis
        Dataanalysis.ShowDialog()
 
I'm a little confused with the formula where you are having the error... In your comment above that line of code, you say:
"'Valve Coefficient formula = cfm / ((valve diameter * 3.14 * lift)*146) * number of valves"
yet the line of code has you dividing instead of multiplying by the "number of valves" (as your comment earlier says that count is this "number of valves"):
"r.Cells(5).Value = CDbl(r.Cells(2).Value.ToString) / ((factor * CDbl(r.Cells(0).Value.ToString)) * 146) / count BLOWS UP HERE"
(BTW jmcilhinney, the count variable is used at the end of the code before the comment "BLOWS UP HERE", although I agree that this shouldn't have tossed this error... Even if nothing was entered into TextBox7, that would still set count=0 and the whole expression = Infinity)

As for why VB doesn't default to having Option Strict turned on, it's because VB was designed as a language for novice programmers. Many wouldn't understand about correct typing of variables and other issues that this option would create, so instead of getting those novices frustrated, they decided to turn it off as default and allow the programmer to turn it on if they feel that they understand programming to a greater degree and would understand the errors in their code when turned on. This is why although VB has this as an option while C# (which is designed more for experienced programmers) don't have an option and always require strict data-typing.
 
Last edited:
I'm a little confused with the formula where you are having the error... In your comment above that line of code, you say:
"'Valve Coefficient formula = cfm / ((valve diameter * 3.14 * lift)*146) * number of valves"
yet the line of code has you dividing instead of multiplying by the "number of valves" (as your comment earlier says that count is this "number of valves"):
"r.Cells(5).Value = CDbl(r.Cells(2).Value.ToString) / ((factor * CDbl(r.Cells(0).Value.ToString)) * 146) / count BLOWS UP HERE"
(BTW jmcilhinney, the count variable is used at the end of the code before the comment "BLOWS UP HERE", although I agree that this shouldn't have tossed this error... Even if nothing was entered into TextBox7, that would still set count=0 and the whole expression = Infinity)

As for why VB doesn't default to having Option Strict turned on, it's because VB was designed as a language for novice programmers. Many wouldn't understand about correct typing of variables and other issues that this option would create, so instead of getting those novices frustrated, they decided to turn it off as default and allow the programmer to turn it on if they feel that they understand programming to a greater degree and would understand the errors in their code when turned on. This is why although VB has this as an option while C# (which is designed more for experienced programmers) don't have an option and always require strict data-typing.

Had I known what it would do to my application's working code.... I would NEVER have turned it on as an afterthought. BIG MISTAKE unless you have a seasoned programmer sitting right there with you to assist in fixing everything it screws up... You have no idea how much work this caused for me and ultimately the bottom line is this. YOU DON'T NEED IT IN EVERY SITUATION.

That said, if it's on from the beginning then YES...great feature. But before advising a green programmer to flip that switch.... STOP and ask them how much code they already have written and advise them to read up on why the feature was added... In my application, after really looking things over and considering what it does... I think I can live without it just fine....
 

Latest posts

Back
Top