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

时间:2017-03-09 00:20:34

标签: 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--)
      {
         catPath[i] = somestring; //fills array
      }
   }

   ...more code...

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

我在catPath事件中使用我的Click数组时遇到问题,它是空的,好像从未在DataBound方法中设置一样。我知道它在Click事件之前设置,因为我在MessageBox方法中使用了DataBound来显示数组中的值,所以我做错了什么?

我尝试过与List类似的东西,但它遇到了同样的问题。其他变量如基本字符串工作正常。

谢谢!

2 个答案:

答案 0 :(得分:3)

ASP.NET是一种Web技术,Web是无状态的,因此您必须以另一种方式维护状态。您必须在ViewState或Session中维护它。所以,ViewState.add("CathPath", catPath)Session.add("CatPath", catPath)。当您在该页面上时,将保留ViewState,当您在应用程序中拥有活动会话时,将保留Session状态。然后你就可以像var catPath = ViewState["CatPath"];

那样访问它

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

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

答案 1 :(得分:0)

除了使用ViewState或Session对象之外,您还可以使用CommandEventArgsCommandEventArgs.CommandArgument

通过绑定项将数据传递到页面
  

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

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

void CommandBtn_Click(Object sender, CommandEventArgs e)
相关问题