MuffinMan
MuffinMan

Reputation: 65

How can I pass a variable from one method to another?

My basic structure:

public partial class _Search : BasePage
{
   private string[] catPath = new string[3]; //set string array

   ...more code...

   protected void Categories_DataBound(object sender, EventArgs e)
   {
      for (int i = 3; i > 0; i--)
      {
         catPath[i] = somestring; //fills array
      }
   }

   ...more code...

   protected void Cat1_Click(object sender, EventArgs e)
   {
      MessageBox.Show(catPath[0]); //uses array
   }
}

I'm having trouble using my catPath array in the Click event, it's empty as if never set in the DataBound method. I know it's set before the Click event because I've used a MessageBox inside the DataBound method to display values from the array so what am I doing wrong?

I've tried something similar with a List but it had the same problem. Other variables like basic strings are working fine though.

Thanks!

Upvotes: 1

Views: 1212

Answers (2)

Dave Anderson
Dave Anderson

Reputation: 12314

In addition to using the ViewState or the Session object you can also pass data to the page through the bound items using CommandEventArgs and the CommandEventArgs.CommandArgument

The CommandArgument can contain any string set by the programmer. The CommandArgument property complements the CommandName property by allowing you to provide any additional information for the command.

When the Page Postback occurs the data is available in the bound event handler. Just ensure the method signature contains the correct EventArgs type and not just the default.

void CommandBtn_Click(Object sender, CommandEventArgs e)

Upvotes: 0

Yatrix
Yatrix

Reputation: 13805

ASP.NET is a web technology and the web is stateless, so you have to maintain state another way. You have to maintain it in ViewState or Session. So, ViewState.add("CathPath", catPath) or Session.add("CatPath", catPath). ViewState will be maintained while you're on that page, Session state will be maintained while you have an active session in the application. Then you can access it like this, var catPath = ViewState["CatPath"];

You can wrap that in a property so you can access it in a similar way to how you would a normal class.

public string[] CatPath {
   get {
      return ViewState["CatPath"];
   };
}

Upvotes: 3

Related Questions