C# 如何将变量从一个方法传递到另一个方法?

C# 如何将变量从一个方法传递到另一个方法?,c#,asp.net,visual-studio-2015,asp.net-4.6,C#,Asp.net,Visual Studio 2015,Asp.net 4.6,我的基本结构: 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--)

我的基本结构:

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
   }
}
Click
事件中使用我的
catPath
数组时遇到问题,它是空的,好像从未在
DataBound
方法中设置过。我知道它是在
单击
事件之前设置的,因为我在
数据绑定
方法中使用了
消息框
,以显示数组中的值,那么我做错了什么


我尝试过类似的列表,但它有同样的问题。不过,基本字符串等其他变量也可以正常工作


谢谢

ASP.NET是一种web技术,web是无状态的,因此您必须以另一种方式维护状态。您必须在ViewState或Session中维护它。因此,
ViewState.add(“catPath”,catPath)
Session.add(“catPath”,catPath)
<代码>视图状态将在您处于该页面时保持,而
会话
状态将在您在应用程序中有活动会话时保持。然后您可以像这样访问它,
var catPath=ViewState[“catPath”]

您可以将其包装在属性中,以便以与普通类类似的方式访问它

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

ASP.NET是一种web技术,web是无状态的,因此您必须以另一种方式维护状态。您必须在ViewState或Session中维护它。因此,
ViewState.add(“catPath”,catPath)
Session.add(“catPath”,catPath)
<代码>视图状态
将在您处于该页面时保持,而
会话
状态将在您在应用程序中有活动会话时保持。然后您可以像这样访问它,
var catPath=ViewState[“catPath”]

您可以将其包装在属性中,以便以与普通类类似的方式访问它

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

除了使用ViewState或Session对象外,还可以使用和通过绑定项将数据传递到页面

CommandArgument可以包含程序员设置的任何字符串。CommandArgument属性通过允许您为命令提供任何附加信息来补充CommandName属性

当页面回发发生时,绑定事件处理程序中的数据可用。只需确保方法签名包含正确的EventArgs类型,而不仅仅是默认类型

void CommandBtn_Click(Object sender, CommandEventArgs e)

除了使用ViewState或Session对象外,还可以使用和通过绑定项将数据传递到页面

CommandArgument可以包含程序员设置的任何字符串。CommandArgument属性通过允许您为命令提供任何附加信息来补充CommandName属性

当页面回发发生时,绑定事件处理程序中的数据可用。只需确保方法签名包含正确的EventArgs类型,而不仅仅是默认类型

void CommandBtn_Click(Object sender, CommandEventArgs e)

“其他变量(如基本字符串)工作正常。”那么,什么类型的变量工作不正常?字符串数组“其他变量(如基本字符串)工作正常”。那么,什么类型的变量工作不正常?字符串数组