skmasq skmasq - 27 days ago 9
Vb.net Question

Variable loses scope when used through button.click handler

When I call my function at

Me.Load
everything is OK, but when I trigger my function only on the button click event all variables inside lose their set values. I just started on VB.NET so I don't fully understand scope nature here.

Here is my code:

Public Class WorkflowForward
Inherits FileBound.Web.FBBasePage

' Private decalrations
Private cfile_id As String = "" ' Current files ID
Private FBProject As Project = Nothing ' FileBound Project object
Private cmd As String = "" ' SQL query string
Private FBFile As FileBound.File = Nothing ' Filebound file holder
Private FBRoutes As RouteCollection = Nothing ' FileBound route collection holder


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

' Set SqlDataSource connection string
FBSqlDataSource.ConnectionString = ConfigurationManager.ConnectionStrings("FB_0371tcc").ConnectionString

If Not Me.IsPostBack Then
' Set values to variables
Page_setup() ' Here I set values to variabels
setRoute_debug("Admin1 Test")

End If


End Sub

Protected Sub sendEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles sendEmail.Click
' CAN I HAZ SOME TEST????
'setRoute_debug(emailTo.SelectedValue.ToString)

Response.Write("<script>" & Me.FBRoutes.TotalCount.ToString & "</script>")

End Sub

Private Sub setRoute_debug(ByVal route_to As String)

' IF WE HAZ SOME ITEMS FINISH THEM MUHUHAHHAHAHA
If FBBusiness.LoggedInUser.RoutedItems.TotalCount > 0 Then
For Each item As RoutedItem In FBBusiness.LoggedInUser.RoutedItems
item.Complete("Completed!")
Next
End If




' DEBUG MODE #YOLO
' I'VE DONE IT I CAN HAZ ROUTEZ
For Each r As Route In Me.FBRoutes
If r.Name = route_to Then
For Each doc As FileBound.Document In FBFile.Documents
doc.Route(r.ID)
Next

End If
Next


End Sub

Private Sub Page_setup()
' Some code that sets values
End Sub
End Class


When I click the button it throws this error:

Object reference not set to an instance of an object.
Line 46: Response.Write("<script>" & Me.FBRoutes.TotalCount.ToString & "</script>")

Answer Source

A button click on as asp.net page would come as a PostBack.

Your are setting up the page only in

If Not Me.IsPostBack

This is fine for asp.net controls, cause they retain their state across PostBacks using the ViewState.

When click a button, server receives a new request, and a new object of Page is created. Your variables are not set for this object.

Set your page level variables on every PostBack, like this

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    ' Set SqlDataSource connection string
    FBSqlDataSource.ConnectionString = ConfigurationManager.ConnectionStrings("FB_0371tcc").ConnectionString

    Page_setup() ' Here I set values to variables

    If Not Me.IsPostBack Then
        'Set Page level control values like TextBox values
    End If
End Sub