FloodMoo
FloodMoo

Reputation: 37

Using local variable in aspx page

I am new to c#.

Is it possible to use a local variable (declared in Page_Load method inside System.Web.UI.Page class) in the .aspx page. or do i have to declare an accessor variable inside "UI.Page" class and use it as reference?

public partial class consoleTours : System.Web.UI.Page
{
   public string AStr{ get; set; }// i could use this
}

protected void Page_Load(object sender, EventArgs e)
{
    string LStr=""; <i>// i couldn't use this
}

Thank you for edit. as to c# i am also new to stackoverflow as you could see. Point of my question is.I couldn't use public property (AStr) for tryParse.i first use local variable for parsing then assign LStr to AStr and use it in the page. so it makes me use 2 variables instead one. I thought there should be another way.

Upvotes: 0

Views: 3633

Answers (2)

Complexity
Complexity

Reputation: 5820

You have 2 valid options 1:

Use a public property on the page:

This is what you have done already:

public class MyPage : System.Web.UI.Page
{
     public string MyPageTitle { get; set; }

}

Now, the property MyPageTitle can be accessed anywhere in your cs file, and can be used in your ASPX file aswell.

If you want to have a property which is accessible on multiple pages, you must play with inheritance:

Use inheritance to create a new Page object:

First, you create class that acts as a Page:

public class ParentPage : System.Web.UI.Page
{
    public string MyPageTitle { get; set; }
}

Now, when you create a new page, your code will look by default like this:

public class MyPage : System.Web.UI.Page
{
}

Change the System.Web.UI.Page to your created ParentPage, so it will looks like the following:

public class MyPage : ParentPage
{
}

Now, in the 'MyPage' class, you will have access to the MyPageTitle property as well as on the aspx file.

Thus, your are exposing a variable to another control by using inheritance.

Upvotes: 1

BossRoss
BossRoss

Reputation: 869

Declare the variable just inside the class and outside of a method

public string LStr=""; 

protected void Page_Load(object sender, EventArgs e)
{
    LStr= "this new value";
}

Upvotes: 0

Related Questions