system.NullReferenceException: Object not set to an instance of an object - vb.net

Dim Permission As String
Dim chk As String = "p"
Permission = (ds.Tables("privilege").Rows(0).Item(0)).ToString
MessageBox.Show(Permission)
Dim PermissionArray() As String = Split(Permission, ":")
For i As Integer = 0 To 36
If PermissionArray(i) = 1 Then
Try
Dim chkBox As CheckBox = CType(Me.Controls(chk & i), CheckBox)
chkBox.Checked = True
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End If
Next
This code gives me the following error in catch, i have googled but nothing is working
This is the error: System.NullReferenceException – Object reference not set to an instance of an object.

As you noted chkBox.Checked throws NullReferenceException, you should evaluate the following line for the error:
Dim chkBox As CheckBox = CType(Me.Controls(chk & i), CheckBox)
' This may throw NullReferenceException if there is no (chk & i) control available
chkBox.Checked = True

Although it turned out not to be your problem this time,
Permission = (ds.Tables("privilege").Rows(0).Item(0)).ToString
is a prime candidate for a system.NullReferenceException. This statement relies on everything in your data set being fully and correctly populated or errors can occur.
If the table "privilege" does not exist in the dataset, or the table is empty, or the first column of the first row is null, you can get exceptions and it will be very hard to tell what is wrong. You should test those conditions before relying on the assignment, so you don't get exceptions.

I'll bet you are missing one or more controls "p0" ... "p35" since blindly build the ID, ask the form for the control of that ID but never check if it was actually found. Try including the value of 'i' in your message when the exception is caught. That'll be the first control you're misisng.
And then, be sure to check the return values of functions you call before you USE those return values.

Related

mshtml.IHTMLDocument returning nothing

I have the below code trying to access a webpage and the program is erroring out at a test for the innerHTML property. Below is the code:
iex = GetObject("new:{D5E8041D-920F-45e9-B8FB-B1DEB82C6E5E}")
iex.visible = True
iex.navigate("https://url.aspx")
While iex.readystate <> 4 Or iex.busy
Application.DoEvents()
End While
Dim htdoc As mshtml.IHTMLDocument = iex.Document
Dim htstring As mshtml.IHTMLBodyElement = htdoc.body
If (InStr(htstring.innerHTML, "An error occured while processing your request") > 0) Then
The last line is where it gets the error. And I have determined that it gets the error because htdoc is nothing, resulting in everything else being nothing. At least, that is what I believe the issue to be.
After further troubleshooting, the below line is what is causing the error.
mshtml.IHTMLBodyElement = htdoc.body
The exception error is:
Message = Exception from HRESULT: 0x800A01B6
Item = In order to evaluate an indexed
property, the property must be qualified and the arguments must be
explicitly supplied by the user.
This was working before IE was updated to IE11 (I don't recall what version it was prior, but I would assume it was IE10).
I don't think I am doing anything wrong, but any help you could provide would be greatly beneficial!

How do I handle NullReferenceException with my code

How do I handle this type of error or exception?
Try
If log.Trim = txtUSN.Text Then
MessageBox.Show("USN found: " & log)
Else
MessageBox.Show("USN not found: " & log)
End If
Catch ex as Exception
MessageBox.Show(ex.Message)
The message was "Object reference not set to an instance of an object."
This is the rest of the code:
Dim log As String
Dim sql As New SqlCommand
sql.Connection = MyConnection
sql.CommandText = "SELECT * FROM dbo.tblAcc WHERE USN = '" & txtUSN.Text & "' "
MyConnection.Open()
log = sql.ExecuteScalar
MyConnection.Close()
The simple answer is your trying to use an object that is nothing. If it's nothing you can't use it, hence "Object reference not set to an instance of an object."
As already mentioned in my comments above, the culprit is: log. I'm not sure where you have declared this or when your using it and how your using it, for all I know it's nothing. If you have more code that would be greatly appreciated as I can point out where it's nothing, until then here's how to get around your issue.
Try
If log IsNot Nothing Then
If log.Trim = txtUSN.Text Then
MessageBox.Show("USN found: " & log)
Else
MessageBox.Show("USN not found: " & log)
End If
Else
MessageBox.Show("Log is NOTHING!")
End If
Catch ex as Exception
MessageBox.Show(ex.Message)
End Try
**EDIT**
After you posted more code in a comment (please post code in the area, not in comment's) it seem's there are a few issue's. You have log defined as a string; when you do this set it to something like: String.Empty instead of nothing. Also you want to sse the ExecuteScalar method to retrieve a single value (for example, an aggregate value) from a database which could be an integer, long, single etc data types. In your query your selecting everything, you can't call ExecuteScalar to return that data... I would recommend looking up information about building queries and executing them, it's to long for me to get in depth with it here.
Happy Coding!
Make sure that (log) is not an empty string.
if not String.IsNullorEmpty(log) then
end if

DataGrid information throwing out 'Object Reference' error.

So. I looked around Stackoverflow before posting this question. I found other Questions, but none of them answered my question.
This is my code:
Sub getData()
ListBox1.Items.Clear()
Dim rowindex As String
Dim found As Boolean = False
Dim actie As String
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells.Item("Column1").Value.ToString.Contains("2014-0" & Date.Today.Month.ToString) Then
rowindex = row.Index.ToString()
found = True
actie = row.Cells("Column2").Value.ToString()
ListBox1.Items.Add(actie)
End If
Next
If Not found Then
MsgBox("Item not found")
End If
End Sub
What this does is calls data from a DataGrid. The issue I am having is on 'ListBox1.items.add(actie)'. If I use a Message Box it works fine until I get to the last one and then it also throws the error. (That'll likely be why it throws the error straight away for the ListBox as it adds them all 'at the same time'). I've tried an 'ELSE' but with the else it just says no data found. I thought a Do Until might have worked but it did not.
Error I am getting is: Object Reference Not Set to an Instance of an Object.
I assume this is going to be something really basic and I'm going to hit myself when I turns out to be extremely basic.

Is it possible to customize error message "Column does not allow nulls" in a datatable?

I have a form with controls bound to a datatable in VB.net.
When keeping empty a field that should be filled, I'm receiving the error message : Column does not allow nulls.
Is it possible to replace this error message string by another one ?
There are a lot of ways when it comes to error handling.
You could get your code to throw a custom error alert:
This will throw an alert with the text: NullCollumContent
Try
'your code here
Catch ex As Exception
Throw New System.Exception("NullCollomContent")
End Try
Also as K3rnel31 explained:
This will just show a simple message box to the user
Try
'your code here
Catch ex As Exception
msgbox("error message here")
End Try
You could also use If statements to check the string:
This if checks the length of the string and checks if its equal to 0:
If Not yourString.Length = 0 Then
'your code here
else
'some error handling here
End If
This if checks if your string is equal to "" which basically means an empty string:
If Not yourString Is "" Then
'your code here
Else
'some error handling here
End If
Try
'your code here to the datatable
Catch ex As Exception
msgbox("changed error string here")
End Try
Thank you all for your answers but that's not really my problem.
Everything is about DataTable Object.
My problem is that I don't know where the exception is raised.
Let me explain.
Assume Column X has AllowDBNull property to false
And I'm not creating manually a new row that I add to the table
Which means I'm not using such code:
Dim NewRow as DataRow = DataTable.NewRow
NewRom.Item("X") = textbox1.text
DataTable.rows.add(NewRow)
If I was using that code, I would have indeed added the Try/Catch
Dim NewRow as DataRow = DataTable.NewRow
NewRom.Item("X") = textbox1.text
try
DataTable.rows.add(NewRow)
catch Ex as Exception
...
end try
I'm using a DataNavigator which adds in a hidden manner the new row to be added to the table.
So, if Column X is empty, he raises by himself the error. It's not an Exception to be handled. It's an error displayed at run time. Programmatically speaking, nothing went wrong at run time. It seems like DataTable object is designed with this feature and default Error Message.
I hope it's clear now.

Runtime COMException Unhandeled

I'm working on an app that writes to excel. The following piece f code is working properly ( it fills the requested cell) but generating a run time exception that I can't get rid of.
For i = 1 To 1000 Step 1
If Not (cPart.Range("A" & i).Value = Nothing) Then
If (cPart.Range("L" & i).Value = Nothing) Then
cPart.Range("L" & i).Interior.ColorIndex = 3
End If
i = i + 1
End If
Next
the exception is: COMException was unhandled :Exception from HRESULT: 0x800A01A8
any help?
That HRESULT means Object Required. So it seems like one or more of the objects you try to operate on don't exist but as the code is written at the moment, it's difficult to be sure which it is. An immediate concern though is that you're comparing values to Nothing, in VB.Net you're supposed to use Is Nothing to check for that. Also, you've already set up the For loop to go from 1 to 1000, with a step of 1 (which you don't need to include since it's the default) but you're then doing i = i + 1 which looks like a mistake?
So fixing that and splitting it up into it's parts it might give you a better idea to what's not working:
For i = 1 To 1000
Dim aRange As Object = cPart.Range("A" & i)
If aRange IsNot Nothing AndAlso aRange.Value IsNot Nothing Then
Dim lRange As Object = cPart.Range("L" & i)
If lRange IsNot Nothing AndAlso lRange.Value Is Nothing Then
Dim interior As Object = lRange.Interior
If interior IsNot Nothing Then
interior.ColorIndex = 3
End If
End If
End If
Next
I've declared the new objects as Object which might need to be changed to the correct data types (depending on your project settings).
Hopefully you should now be able to run through the code without error and you should also be able to step through the code and find that one of the new objects (aRange, lRange and interior) is Nothing at some point when it shouldn't be which will show you why it threw that error before.
Another advantage to splitting up the code like this is that you'll now be able to dispose of the Excel objects properly so that the Excel instance can shut down cleanly. See this Q&A for info: Excel.Range object not disposing so not Closing the Excel process