-7

I have a variable which I have declared outside all methods/functions:

public partial class page : System.Web.UI.Page
{
  string query;

 protected void btn_1_Click(object sender, EventArgs e)
 {
   query = "hi";
   query = query + "how are you";
 }

 protected void btn_2_Click(object sender, EventArgs e)
 {
   string newquery = query;
 }
}

When I debug this in the btn_2_Click when it has been fired it says the query variable is null. I am trying to access the query made from btn_1 in btn_2.

What is the best way to do this? Or am I doing something wrong?

Cameron
  • 2,574
  • 22
  • 37
c0mrade
  • 87
  • 9
  • @Cameron I haven't intended to duplicate anything. Btw non of your links describe my situation. – c0mrade Apr 24 '15 at 19:30
  • It's not a big deal to have a duplicate. These are just similar questions and answers that are similar to your situation. And in both of these questions that I've added, their solutions will solve your problem. – Cameron Apr 24 '15 at 19:34
  • @Cameron And this is where all people like you go wrong. You say that would solve my question right? Well, what happens if someone didn't know what the solution did? Or how to implement that solution in to what they are trying to do? The way half of you people see it is "Oh, its the same question" *mark duplicate* but no one ever thinks why the dude is asking that question in the first place – c0mrade Apr 24 '15 at 19:39
  • @Cameron BTW: Just to let you know since you like to comment "duplicate" and claim they all are solutions. Well, I can't get it working. – c0mrade Apr 24 '15 at 19:55
  • 2
    Cameron's second link explains the problem: you need to read up on how ASP.NET page lifecycle works. – Roger Lipscombe Apr 24 '15 at 19:59
  • All that is being said is that WebForms does not mantain variable state between requests and each event is a new request to the same page. Take a look at ASP.Net page lifecycle as suggested by Roger. – Ricardo Souza Apr 24 '15 at 20:17

1 Answers1

1

You can't do that in ASP.Net WebForms. WebForms are not like WindowsForms.

When you click a button on a page, it's click event is fired and all previous information state is lost if not saved to something that can persist requests, like a Session, Application, Cookie, Viewstate, Database, etc.

This link has many possible solutions: https://msdn.microsoft.com/en-us/magazine/cc300437.aspx

Ps.: Don't be offended to have a question marked as a duplicate. This is very common and, althrough not exactly the same question bein made, the solution or clarification from that answers can help you in this question.

Ricardo Souza
  • 16,030
  • 6
  • 37
  • 69