Monday, March 26, 2012

Object reference not set to an instance of an object

Hi Guys

I keep getting this message when i go into one form. The problem is that another screen that looks extactly the same, is able to go in, but not this one.

The message always comes up with:

Object reference not set to an instance of an object.

The code where this appearing is:


Public Class Units
Inherits System.Windows.Forms.Form
Private connunitstring As String = "Server=Test;database=Info;Pwd=Test;User Id=Mis;"
Private dsfac As DataSet
Private fac_code As String
Private fac_desc As String
Private dtunit As DataTable
Private daunit As SqlDataAdapter
Private daFacDept As SqlDataAdapter
Private dvFacDept As DataView
Private dsFacDept_codesearch As New DataSet()

Property facdeptcode() As String
Get
Return (fac_code)
End Get
Set(ByVal Value As String)
fac_code = Value
End Set
End Property

Property facdepttext() As String
Get
Return fac_desc
End Get
Set(ByVal Value As String)
fac_desc = Value
End Set
End Property

Property FacDeptSearch() As DataSet
Get
Return dsFacDept_codesearch
End Get
Set(ByVal Value As DataSet)
dsFacDept_codesearch = Value
End Set
End Property

Sub CreateFacDeptBindComboBox()
Dim sqlFacstr As String = "Select F_desc,F_Dept from Fac_Dept order by F_Dept"

Try
Dim connunit As New SqlConnection(connunitstring)
Dim cmdFac As New SqlCommand(sqlFacstr, connunit)

cmdFac.CommandType = CommandType.Text

daFacDept = New SqlDataAdapter(cmdFac)
dsfac = New DataSet()
daFacDept.Fill(dsFacDept_codesearch, "Fac_Dept")
Dim mygrow As DataRow
For Each mygrow In FacDeptSearch.Tables("Fac_Dept").Rows
CmbFaculty.Items.Add(CType(mygrow.Item(0), String))
CmbFaculty.SelectedIndex = 0
Next

Catch exp As Exception
MsgBox(exp.Message.ToString)
End Try
End Sub

Private Sub Units_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
CreateFacDeptBindComboBox()
End Sub

Any help on this would be appricated.

Regards

ChrisCan you throw us a bone here and let us know EXACTLY what line the error occurs on?
Sorry Forgot to say which line the error occurs in.

When i run the debugger, the error occurs at

CMBFaculty.selectedindex = 0
Where does this object -

CmbFaculty
- come from? Object reference not set to an instance of an object usually indicates that you are attempting to use a reference object that does not point to anything. It is like attempting the following...


Public Sub SomeRoutine()
' Wrong
Dim dbConn As SqlConnection

' Correct
' Dim dbConn As SqlConnection = New SqlConnection()"

dbConn.Open()

' Do some data stuff
dbConn.Close()
End Sub

Clearly you cannot open the connection if there's nothing to open :)

-BC

0 comments:

Post a Comment