Click here to Skip to main content
15,895,256 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Dear Coders,

I have given the code below which i was working. All goes well but when existing the program a null exception error happens with the message "Object reference not set to an instance of an object"

Please help

VB
Dim con As New SqlConnection
        Dim myconstring As String = "Data Source=ETA-TESTSRVR;Initial Catalog=Procurement;Integrated Security=True"
        con.ConnectionString = myconstring
        Dim sql As String = "SELECT mat_sub_no FROM e1 where project_id='" + ComboBox1.SelectedValue.ToString + "'"
        If sql.Length = 0 Then
            MessageBox.Show(sql.Length.ToString)
        End If
        Dim da As New SqlDataAdapter(sql, con)
        Dim dt As New DataTable
        da.Fill(dt)
        ListBox1.DataSource = dt
        ListBox1.DisplayMember = "Mat_Sub_no"
End Sub
Posted
Updated 7-Nov-12 0:57am
v2

SQL
object obj =  ComboBox1.SelectedValue;
if(obj != null)
  Dim sql As String = "SELECT mat_sub_no FROM e1 where project_id='" + obj.ToString + "'"

use this code, it might be work with you.
 
Share this answer
 
"Object reference not set to an instance of an object" error occurs when try to get/set null value.

In your code , this situation might be occurs many places

1.
C#
ComboBox1.SelectedValue.ToString 
ComboBox1.SelectedValue does not fetch any value.

2.
C#
da.Fill(dt)
when you try to fill data adapter

..............

so, better to debug your code to find actual place of source of error

or use try, catch block with your code

1 more thing-

always use
C#
Convert.Tostring()
in the place of
C#
yourvalue.ToString()
 
Share this answer
 
Comments
armarzook 7-Nov-12 7:21am    
Actually the error is showing in this line.

Dim sql As String = "SELECT mat_sub_no FROM e1 where project_id='" + ComboBox1.SelectedValue.ToString + "'"
If you have put this code inside New() method [Constructor]
then
make sure you have called InitializeComponents() before code

else

put code inside this condition
VB
If ComboBox1.SelectedValue Isnot Nothing then
 .... 'your code
End If

Happy Coding!
:)
 
Share this answer
 
Comments
armarzook 10-Nov-12 8:38am    
If ListBox1.SelectedValue Is Nothing Then
Me.E1TableAdapter.FillBy(Me.ProcurementDataSet.E1, projid:=CType(TextBox1.Text, Integer))
Else
MsgBox(ListBox1.SelectedValue)
Me.E1TableAdapter.FillBy1(Me.ProcurementDataSet.E1, ms_no:=ListBox1.SelectedValue)
End If

Already tried this.... No solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900