Thursday, March 29, 2012

Object reference error

Private Sub cmdLeftRight_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles cmdLeftRight.Click, cmdCenterRight.Click, cmdCenterLeft.Click, cmdRightLeft.Click

Dim sourcePane As String = CType(sender, ImageButton).Attributes("sourcepane")
Dim targetPane As String = CType(sender, ImageButton).Attributes("targetpane")
Dim sourceBox As ListBox = CType(Page.FindControl(sourcePane), ListBox)
Dim targetBox As ListBox = CType(Page.FindControl(targetPane), ListBox)

end sub

why i can not find my control with the "Page.FindControl" method?
the string name is correcte, the control exist on my page. I still have that error "object reference not set to an instance of..object"

what do i do wrong here !!

thanxYou haven't provided enough information for us to answer your question. Whether Page.FindControl will actually find a control depends on where the control is on your page.

To see what I mean - and hopefully to allow you to solve your own problem - please read:
In Search Of Controls

As an aside, you should always test whether an object has a value before you start working with it.

For example, you should do something like:

' Find the target pane
Dim FoundTargetPane As Control
FoundTargetPane = Page.FindControl( targetPane )

' If found, cast the target pane to a ListBox control
Dim targetBox As Listbox
If Not FoundTargetPane Is Nothing Then
targetBox = CType( FoundTargetPane, ListBox )
End If

' Work with the targetBox
If Not targetBox Is Nothing Then
' we can work with targetBox, knowing that's we've found it
End If

0 comments:

Post a Comment