user3467273
user3467273

Reputation:

How to use Global Variables in C#

Here is my code

public partial class Books : System.Web.UI.Page
{
    String Book_CategoryName = "";
    String Book_SubCategoryName = "";

   protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Book_CategoryName = "Education";
        }
    }
    public void BookDataLinkButton_Click(object sender, EventArgs e)
    {
        Response.Write("Data Found :: "+Book_CategoryName);
    }

}

In this code i use global variable, on page_load set the value of Book_CategoryName variable and try to get on LinkButton click. But i am unable to get the "Education" . When i run this code it show me Data Found ::

How can i get the value of Book_CategoryName variable.

Try to help me out of this problem.

Upvotes: 0

Views: 2047

Answers (3)

PEO
PEO

Reputation: 195

Change your variable like following

static String Book_CategoryName = "";    
static String Book_SubCategoryName = "";

Upvotes: 0

JW Lim
JW Lim

Reputation: 1814

That's because the page object called is different for each web request. Hence, when you initialize Book_CategoryName in Page_Load, it is only valid for that request and the value is lost in the next request i.e. when BookDataLinkButton_Click is called.

In your case, you could simply initialize the variable during declaration, like so:

String Book_CategoryName = "Education";

You can take a look at this question for more information.

Alternatively, you can use the ViewState instead of a "global variable"

protected void Page_Load(object sender, EventArgs e)
{
     if (!Page.IsPostBack)
     {
         ViewState["Book_CategoryName"] = "Education";
     }
}

public void BookDataLinkButton_Click(object sender, EventArgs e)
{
     Response.Write("Data Found :: " + (string)ViewState["Book_CategoryName"]);
}

Upvotes: 1

Teddy
Teddy

Reputation: 1417

On each post back, the instance of Page(Books) is re-created, so you will not get the value of Book_CategoryName after button click. An approch is to store the variable in ViewState.

private const string KEY_Book_CategoryName = "Book_CategoryName";
public String Book_CategoryName
{
    get
    {
        return ViewState[KEY_Book_CategoryName] as string;
    }
    set
    {
        ViewState[KEY_Book_CategoryName] = value;
    }
}

The other approch can be store the value in a hidden field of the page. The idea is to store the value somewhere that can persistent during post back.

Upvotes: 2

Related Questions