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.

有帮助吗?

解决方案

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.

其他提示

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"]);
}

Change your variable like following

static String Book_CategoryName = "";    
static String Book_SubCategoryName = "";
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top