"NullReferenceException was Unhandled" - visual-studio-2010

I have a project here in my ojt. vb2010 form. I am getting this error:
"NullReferenceException was Unhandled"
Why do I get it?
this is my code;
Private Sub RefreshData()
If Not con.State = ConnectionState.Open Then
con.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("SELECT ID as [ID], " & _
"fname as [NAME], lname" & _
"FROM asdf ORDER by ID", con)
da.Fill(ds.Tables("asdf"))**** this part is where i get the error*****
con.Close()
End Sub

Error says what it means,
Put a null check
if(ds != null && ds.Tables("asdf") != null) then
.... ' put da.Fill here
end if

"NullReferenceExeption was Unhandled" error indicates that you are trying to use a null object in the code. Do a null check like:-
if(con != null) then
'your code...
end if
if(ds != null && ds.Tables("asdf") != null) then
'your code...
end if

Related

No Value given for one or more required parameters in Vb6

I'm new to Vb6.
I haven't inserted data in my database and when I run the program, an error shows No Value given for one or more required parameters
Here's the code:
Dim list As ListItem, r As Integer
If recset.State = adStateOpen Then recset.Close
recset.Open "SELECT StudentId, LastName, FirstName, MiddleName FROM Students ORDER BY StudentId", rainCon, adOpenStatic, adLockOptimistic
If recset.RecordCount > 1 Then
MsgBox "No Data Found!", vbInformation, ""
Else
ListView1.ListItems.Clear
Do While Not recset.EOF
r = r + 1
Set list = ListView1.ListItems.Add(, , r)
list.SubItems(1) = recset(0).Value
list.SubItems(2) = recset(1).Value
list.SubItems(3) = recset(2).Value
list.SubItems(4) = recset(3).Value
recset.MoveNext
Loop
End If
Then highlights recset.Open part. How to control or fix this error?
When I tried to re-check my code and database multiple times. I found out that there was a missing attribute in my students table. The code was fully functional.
Find out the full working code.
Private Sub cmdAddItemtoListBox_Click()
'Enter Code here....
End Sub
Change database path, name, and table as per your data.
Output Screenshot
Dim xCon As New ADODB.Connection
Dim rsTable As New ADODB.Recordset
Dim StrSqlQuery As String
Dim Counter As Integer
Dim list As ListItem
If xCon.State = 1 Then xCon.Close
xCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Test\Test.mdb;Persist Security Info=False"
'
StrSqlQuery = ""
StrSqlQuery = "Select * from Data Order by PrintSl"
If rsTable.State = 1 Then rsTable.Close
rsTable.CursorLocation = adUseClient
rsTable.Open StrSqlQuery, xCon, adOpenStatic, adLockReadOnly
If rsTable.RecordCount > 0 Then
rsTable.MoveFirst
ListView1.ListItems.Clear
ListView1.ColumnHeaders.Add , , "ID"
ListView1.ColumnHeaders.Add , , "Customer Name"
ListView1.ColumnHeaders.Add , , "Address"
ListView1.ColumnHeaders.Add , , "Pincode"
ListView1.ColumnHeaders.Add , , "Amount"
Do While Not rsTable.EOF
Counter = ListView1.ListItems.Count + 1
Set list = ListView1.ListItems.Add(, , Counter)
list.ListSubItems.Add , , rsTable!CUSTOMERNAME
list.ListSubItems.Add , , rsTable!ADDRESS1
list.ListSubItems.Add , , rsTable!pin
list.ListSubItems.Add , , rsTable!LOAN_AMOUNT
rsTable.MoveNext
Loop
Else
MsgBox "No record found in the table.", vbCritical
End If
If rsTable.State = 1 Then rsTable.Close
If xCon.State = 1 Then xCon.Close
MsgBox "Record Add Successfully", vbInformation

BC42104 error code how can I fix this error?

Warning BC42104: Variable 'pass' is used before it has been assigned a value. A null reference exception could result at runtime.
This is my code:
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim uname As String = ""
Dim pword As String
Dim username As String = ""
Dim pass As String
If TextBox1.Text = "" Or TextBox2.Text = "" Then
MsgBox("Please fill the info")
Else
uname = TextBox1.Text
pword = TextBox2.Text
Dim query As String = "Select Password From Register where Username= '" & uname & "';"
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Gui\Documents\Database4.accdb"
Dim conn = New OleDbConnection(dbsource)
Dim cmd As New OleDbCommand(query, conn)
conn.Open()
Try
pass = cmd.ExecuteScalar().ToString
Catch ex As Exception
MsgBox("Username does not exit")
End Try
If (pword = pass) Then
MsgBox("Login success")
Reg.Show()
If Reg.Visible Then
Me.Hide()
End If
Else
MsgBox("login Failed")
TextBox1.Clear()
TextBox2.Clear()
End If
End If
End Sub
As the error is saying, you are not initializing the variable pass and under some condition, you may end up with using it.
To be exact, if the control lands in the 'catch' block, the variable 'pass' will not have any values, which means it is possible that If (pword = pass) statement is reached without this variable having any values.
To fix the error, just assign a null value or empty string to the variable at the point of initialization. For example use this statement:
Dim pass As String = "";

How to use DataReader from Oledb and get results in Richtextbox

Dim srch As String
srch = ccode.Text
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + IO.Directory.GetCurrentDirectory + "\ptdr.accdb"
cmd.Connection = conn
conn.Open()
Dim dsrch As New OleDbCommand("SELECT pname, page, vdate, psex, summer, bldp, blds, photh, diag, rl, trtmnt, nvdate FROM ptnt_data WHERE pcode = " & srch & "", conn)
Dim rdr As OleDbDataReader = dsrch.ExecuteReader()
Dim dg As String = ""
'diagnosis'
dg = rdr.GetString(8).ToString()
If String.IsNullOrEmpty(dg) Then
diag1.Text = ""
ElseIf String.IsNullOrWhiteSpace(dg) Then
diag1.Text = ""
Else
diag1.Text = dg
End If
It works fine but when I search for a null it gives an error.
It says that I've an error at the line of
dg = rdr.GetString(8).Tostring()
any suggests?
rdr.GetString(8).ToString()
if rdr.GetString(8) is null this is a classic null reference exception
rdr.GetString(8) IS a string so just remove the .ToString()
As per my comment below you can only run GetString if the DB has an underlying type of string for this data, what is the datatype of column diag?
(ie run rdr.GetFieldType(8) in the debugger and provide the type name)
As you have confirmed this is a string type and the issue is just with null handling (sorry i didn;t spot that from your question) you need:
If rdr.IsDBNull(8) Then diag1.Text = "" Else diag1.Text = rdr.GetString(8) EndIf
Which should replace everything from Dim dg... down

compiler error when i run my program

Private Sub Form_Activate()
Dim st1 As String
'if txtmode 1 fetch record of id from database
If txtmode.Text = "1" Then
'SQL statement
openCon
st1 = "SELECT Customer_name, Address1, Address2, City, Contact FROM customer WHERE id=" & txtid.Text
recSet.Open st1, conn, adOpenDynamic, adLockOptimistic
recSet.MoveFirst
If recSet.Fields("Customer_name").Value <> vbNullString Then
txtCustomer_name = recSet.Fields("Customer_name").Value
Else
txtCustomer_name = ""
End If
When I run my program, I get an error:
compiler error : invalid use of property on txtCustomer_name = line
Why? and how can I solve it ?
You can try this:
If IsNull(recSet.Fields("Customer_name").Value) Then
txtCustomer_name.Text = ""
Else
txtCustomer_name.Text = recSet.Fields("Customer_name").Value
End If

stackoverflow exception with htmlagility pack

I am using the htmlagilitypack to parse an xml document. I use it to load the string as a htmldocument and then use the xmltextreader to parse. I will occasionally get an unhandled stackoverflow exception on htmlagility.dll.
The specific line is
internal Dictionary<string, Htmlattribute> Hashitems = new
Dictionary<string, HtmlAttribute>()
EDIT:
Try
Dim hdoc = New HtmlAgilityPack.HtmlDocument()
hdoc.LoadHtml(xmlsnippet)
Dim nreader As XmlTextReader = New
XmlTextReader(New StringReader(xmlsnippet))
Dim ncount As Integer = 0
While nreader.Read
If Not nreader.Name = "" Then
ncount += 1
If ncount = 18 Then
Exit While
End If
num += 1
nodelist.Add(nreader.Name)
If nreader.Name = "id" Then
statid = nreader.ReadInnerXml
End If
If nreader.Name = "published" Then
contentDate = nreader.ReadInnerXml
contentDate = Regex.Replace(contentDate, "T", " ")
contentDate = Regex.Replace(contentDate, "\+", " ")
contentDate = contentDate.Replace("Z", "")
End If
If nreader.Name = "summary" Then
ctext = nreader.ReadInnerXml
End If
If nreader.Name = "title" Then
csubject = nreader.ReadInnerXml
If csubject.Contains("posted") Then
template = csubject
author = Regex.Replace(template, "posted.*", "")
End If
If csubject.Contains("Keyword -") Then
Dim tip As String = csubject
searchterm =
Regex.Replace(csubject, "xxxxxx.*xxxxxx.*xxxx.*-", "")
searchterm =
Regex.Replace(searchterm, "xxxxx.*xxxxxx.*Search.*-", "")
Trim(searchterm)
End If
End If
End If
End While
Dim mreader As XmlTextReader =
New XmlTextReader(New StringReader(xmlsnippet))
Dim mcount As Integer = 0
While mreader.Read
If Not mreader.Name = "" Then
mcount += 1
If mcount > 15 Then
If mreader.Name = "uri" Then
authorUri = mreader.ReadInnerXml
Trim(authorUri)
If authorUri = "http://www.xxxxxxxx.com/" Then
authorUri = ""
End If
End If
If mreader.Name = "name" Then
author = mreader.ReadInnerXml
If author = "xxxxxx" Then
author = ""
End If
End If
If mreader.Name = "content" Then
htext = mreader.ReadInnerXml
End If
If mreader.Name = "link" Then
Dim address As String
address = mreader.ReadOuterXml
If address.Contains("related") Then
Dim regex12 As Regex =
New Regex("<link.*rel.*href=""(?<Link>.*?)"".*/>", RegexOptions.IgnoreCase)
Dim m12 As Match = regex12.Match(address)
himage = m12.Groups("Link").Value
ElseIf address.Contains("alternate") Then
Dim regex13 As Regex =
New Regex("<link.*rel.*href=""(?<Link>.*?)"".*/>", RegexOptions.IgnoreCase)
Dim m13 As Match = regex13.Match(address)
authorUri = m13.Groups("Link").Value
End If
End If
If mreader.Name = "subtitle" Then
hsubtitle = mreader.ReadInnerXml
End If
End If
End If
End While
Catch ex As Exception
appLogs.constructLog(ex.Message.ToString, True, True)
Exit Sub
End Try
In fact there are different stackoverflow exception errors occurring at different lines but the same error and only while using htmlagilitypack. I am in another method trying to parse the xml using xmldocument, xpathnavigator and it works fine unless I get some bad xml, then I go to this method. I have set up exception catches to just move the bad xml to a folder and then exit this method but I cannot catch these kinds of exceptions or can I?
Another line where error shows:
public string Name
{
get
{
if (_name == null)
{
Name = _ownerdocument.Text.Substring(_namestartindex, _namelength);
}
return _name != null ? _name.ToLower() : string.Empty;
on the last line in the snippet above in the file HtmlNode.cs.
The call stack window shows the top as
HtmlAgilityPack.dll!HtmlAgilityPack.HtmlNode.Name.get() Line 432 + 0x21 bytes

Resources