【问题标题】:How can I pass a variable from one method to another?如何将变量从一种方法传递给另一种方法?
【发布时间】:2017-07-29 19:05:23
【问题描述】:

我的基本结构:

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 方法中设置过一样。我知道它是在 Click 事件之前设置的,因为我在 DataBound 方法中使用了 MessageBox 来显示数组中的值,所以我做错了什么?

我尝试过使用 List 进行类似的操作,但遇到了同样的问题。不过,基本字符串等其他变量也可以正常工作。

谢谢!

【问题讨论】:

  • " 但其他变量(如基本字符串)运行良好。"那么什么类型不能正常工作呢?
  • 字符串数组

标签: c# asp.net visual-studio-2015 asp.net-4.6


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

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

    void CommandBtn_Click(Object sender, CommandEventArgs e)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-20
      • 1970-01-01
      • 2018-12-24
      • 2018-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多