I am using Visual Studio 2008 SP1, ASP.NET, and VB.NET.

I am using a wizard, and in order to affect the controls inside it, I have to declare them in each method like so:

Dim txtbox1 As TextBox = wizard.ContentTemplateContainer.FindControl("textbox1")

Which works fine, but sometimes I need to access that same control across different methods, thereby requiring me to declare it for each one individually.

Making my question:
Is there a way to declare each control like that once, for the entire codebehind page/class?


You can declare like this.

Partial Class YourPage
    Inherits System.Web.UI.Page

    Dim txtbox1 As TextBox
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        txtbox1 = Wizard.ContentTemplateContainer.FindControl("textbox1")
    End Sub

    Private Sub YourMethod()
        Dim str1 As String
        str1 = txtbox1.Text

    End Sub
End Class

The variable is declared at page class level. The reference of the textbox1 control is stored in page load event. It is accessed in YourMethod(). Like that you can access the variable txtbox1 in all methods in the page class.

commented: Awesome post! Well put, easy to understand. Thanks! +2

Thanks! Worked a treat!

I was pretty sure it would be something painfully obvious like that.