DataGrid information throwing out 'Object Reference' error. - vb.net

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.

Related

Checking if element exists VBA Selenium

Looking for help on how to implement VBA code to check if an element exists or explicitly waiting for it in VBA. Here is a small sample code I am testing out. The below code gives an error while running since it says "Object Required"
Dim Driver As New ChromeDriver
Driver.get "Test website"
If Driver.IsElementPresent(By.XPath("/html/body/div[2]/div/div[5]/h3"))) Then
Debug.Print("Yes")
Else
Debug.Print("No")
I even have tried changing the .IsElementPresent to this line of code so I can test the size of the element if it exists but receiving an error that "NoSuchElementError"
Debug.Print (browser.FindElementByXPath("/html/body/div[2]/div/div[5]/h3").Size())
Seem to work for me. The only issue I am seeing in your code is that you didn't declare By anywhere.
e.Start isn't a requirement, but I do it anyway.
So I would try declaring By and see what happen there. And you need to set it as a new instance, a simply type-declaration won't work, which means:
Just using Dim By As Selenium.By is NOT enough, but either of these lines:
Dim By As New Selenium.By
or
Dim By As Selenium.By
Set By = New Selenium.By
The Object Required error you are receiving is likely due to the missing declaration I stated above.
As text above, for me it worked like this...
Dim ch As Selenium.ChromeDriver
Set ch = New Selenium.ChromeDriver
'... all code ...
If ch.IsElementPresent(FindBy.XPath("//*[#id='div_footer']/table/tbody/tr/div")) Then
ch.FindElement(FindBy.XPath("//*[#id='div_footer']/table/tbody/tr/div")).Click
ElseIf ch.IsElementPresent(FindBy.XPath("//*[#id='xlsbutton']")) Then
ch.FindElement(FindBy.XPath("//*[#id='xlsbutton']")).Click
Else
'nohing here, only to understand stament
boolean_check_Download_Click_XYZ = false
End If

Creating a new IUI Automation Handler object in order to subscribe to an automation event

So, here it goes. To start, A disclaimer, I understand that MS Access is not built for this kind of work. It is my only option at this time.
I have done just a bit of Automation using UIAutomationClient and I have successfully used its other features, however I cannot for the life of me get it to subscribe to events.
Normally, it is supposed to be a bit like this:
Dim CUI as new CUIAutomation
Dim FocusHandler as IUIAutomationFocusChangedEventHandler
Set FocusHandler = new IUIAutomationFocusChangedEventHandler(onFocusChanged)
C.AddFocusChangedEventHandler(Element,TreeScope_Children, null, FocusHandler)
end function
'
'
Function onFocusChanged(src as Object, args as AutomationEventArgs)
''my code here
end function
Yet when I attempt this, I get the error "expected end of statement" on the line:
FocusHandler = new IUIAutomationFocusChangedEventHandler(onFocusChanged)
additionally, if I leave off the (onFocusChanged) I get the error "Invalid use of new Keyword".
It seems like I am missing a reference somewhere. The usual drop down when using "new" does not contain the IUI handler classes though they are in the object library.
I am not sure if there is just some piece I am not accounting for in the code since I am using vba, but all examples seem to be for .net or C#/C++. Any help would be appreciated.
Additionally, I have no problem finding the element in question and all other pieces work fine. If you need any other pieces of the code let me know.
Edit: added set to line 3. No change in the problem though.
After two years this probably isn't relevant any more, but perhaps somebody else encounters this problem... The answer is to create a new class that implements the HandleAutomationEvent method.
Here I created a class named clsInvokeEventHandler and (importantly) set the Instancing property to PublicNotCreatable:
Option Explicit
Implements IUIAutomationEventHandler
Private Sub IUIAutomationEventHandler_HandleAutomationEvent(ByVal sender As UIAutomationClient.IUIAutomationElement, ByVal eventId As Long)
Debug.Print sender.CurrentName
End Sub
And to use it:
Sub StartInvokeHandler()
Dim oUIA As New CUIAutomation8
Dim oRoot As IUIAutomationElement
Dim InvokeHandler As clsInvokeEventHandler
Set InvokeHandler = New clsInvokeEventHandler
Set oRoot = oUIA.GetRootElement
oUIA.AddAutomationEventHandler UIA_Invoke_InvokedEventId, oRoot, TreeScope_Descendants, Nothing, InvokeHandler
End Sub

"Object reference not set to an instance of an object" message

I keep getting window that pops up when I run a VB.NET console program I made that simply says "Object reference not set to an instance of an object." The window doesn't even say "error" or anything--the title is simply the name of the project. However...I'm assuming this is something I don't want.
I searched around a bit and found posts about similar messages but couldn't figure out how they applied to my situation.
Here is some of my code. (This program is supposed to take some data from a preformatted text file that describes the geometry of a cross section of a river and systematically enters some new geometric data to represent the riverbed being cleaned/cleared out in a certain way, and then write the new data to a new file in a similar format.)
Imports System
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Module module1
Public Sub Main()
Using sr As New StreamReader("C:\inputfile.txt")
Using outfile As New StreamWriter("C:\outputfile.txt")
Dim line As String = ""
Dim styles As Globalization.NumberStyles
styles = Globalization.NumberStyles.AllowLeadingSign Or Globalization.NumberStyles.AllowDecimalPoint
Dim stations(-1) As Double
Dim elevations(-1) As Double
Dim i As Integer = 0
Do
Try
line = sr.ReadLine()
Dim stringarray() As String = line.Split()
ReDim Preserve stations(i)
ReDim Preserve elevations(i)
stations(i) = Double.Parse(stringarray(0), styles)
elevations(i) = Double.Parse(stringarray(1), styles)
Catch ex As Exception
MsgBox(ex.Message)
End Try
i = i + 1
Loop Until line Is Nothing
Dim min As Double = elevations(0)
(some more code.....)
End Using
End Using
End Sub
End Module
I only included the first part of my code because when I put a break at the "Loop Until line Is Nothing" statement, the message didn't come up until after I went through the break, but when I put the break at the "Dim min As Double = elevations(0)" statement, the message came up before the program got to the break.
I don't really get what's wrong with my code. Anyone have any ideas?
Thanks!
See if this works any better:
Public Sub Main()
Dim styles As Globalization.NumberStyles = Globalization.NumberStyles.AllowLeadingSign Or Globalization.NumberStyles.AllowDecimalPoint
Dim stations As New List(Of Double)
Dim elevations As New List(Of Double)
For Each line As String in File.ReadLines("C:\inputfile.txt")
Try
Dim stringarray() As String = line.Split()
stations.Add(Double.Parse(stringarray(0), styles))
elevations.Add(Double.Parse(stringarray(1), styles))
Catch ex As Exception
MsgBox(ex.Message)
End Try
Next Line
Dim min As Double = elevations(0)
Using outfile As New StreamWriter("C:\outputfile.txt")
End Using
End Sub
Note that I moved your output file to the end... you haven't written anything yet, and so it's a good idea to wait as long as possible to open it, to keep it open for as short a time as possible.
The code fails after the last line has been read because the exit condition (Loop Until) doesn't know that you have reached the end of file. So another loop is started and the code tries to read an inexistent line. The last ReadLine returns Nothing, but the code tries to split it.
You could add a check before trying to split the line and jump directly to the Loop Until statement if you don't have anymore lines to read. Of course I also suggest to remove the array redim at every loop and use a more flexible List(Of Double)
Dim stations = New List(Of Double)
Dim elevations = New List(Of Double)
Do
Try
' After the last line this command returns null (Nothing in VB)
line = sr.ReadLine()
if line IsNot Nothing Then
Dim stringarray() As String = line.Split()
stations.Add(Double.Parse(stringarray(0), styles))
elevations.Add(Double.Parse(stringarray(1), styles))
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Loop Until line Is Nothing
OK...I feel really dumb now...after reading through all of your answers and looking at Steve's code, I realized my code was going through the loop one last time where "line" was set as nothing at the beginning of the loop and it was still trying to add "nothing" as an element to the arrays. The key to fixing it was adding an "If line IsNot Nothing" statement before the statements adding elements to the arrays, which Steve had.
Thank you all for your answers!

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

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.

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