2013-01-22 55 views
0

當我在Me.Load處調用我的函數時,一切正常,但是當我僅在按鈕單擊事件時觸發我的函數時,所有變量都會丟失其設置值。我剛開始使用VB.NET,因此我不完全瞭解範圍性質。當通過button.click處理器時,變量丟失範圍。點擊處理器

這裏是我的代碼:

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 

當我點擊它拋出這個錯誤按鈕:

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

回答

1

點擊一個按鈕上的asp.net頁面會來爲PostBack

你只在

If Not Me.IsPostBack 

這是罰款asp.net控件設置的頁面,因爲他們整個使用ViewState回傳保持其狀態。

當點擊一個按鈕時,服務器會收到一個新的請求,並創建一個新的Page對象。您的變量未針對此對象設置。

設置你的頁面級變量在每次回傳,這樣

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 
+0

輝煌!謝謝。 – skmasq