【问题标题】:Global variable empty in page load页面加载时全局变量为空
【发布时间】:2013-08-09 10:39:58
【问题描述】:

我在页面中创建了一个列表作为全局变量。

public static List<LinkButton> allControlsLinkButtonSalles = new List<LinkButton>();

Page_Load 期间调用的函数中,我添加了一些这样的元素:

foreach (var childControl in allControlsLinkButton)
{
    if (childControl.CssClass == "linkButtonSalleActive" ||  childControl.CssClass == "linkButtonSalle")
    {
        allControlsLinkButtonSalles.Add(childControl);
    }
}

就在那之后,当我这样做时:

foreach (LinkButton value in allControlsLinkButtonSalles)
{
    literal2.Text += " <br /> Text " + value.Text;
}

而且肯定会出现 3 个元素。 但是,当我尝试这样做时:

literal2.Text += " First element " + allControlsLinkButtonSalles.First().Text;

发生错误。这怎么可能?

这是消息:

说明:在执行当前 Web 请求期间发生未处理的异常。检查堆栈跟踪以获取有关错误及其在代码中的位置的更多信息。

异常详情:System.InvalidOperationException:序列不包含任何元素。

来源错误:

莱茵 605 : } 利涅 606: Ligne 607:literal2.Text +=“第一”+ allControlsLinkBut​​tonSalles.First().Text; 利涅 608: Ligne 609 : //allControlsLinkBut​​tonSalles[0].CssClass = "linkBut​​tonSalleActive"; 堆栈跟踪:

[InvalidOperationException:序列不包含任何元素。] System.Linq.Enumerable.First(IEnumerable `1 源)+269 c:\Users....\Documents\Visual Studio 2012\WebSites\test1\test2MasterPage.aspx.cs:607 中的 test2MasterPage.Page_init() System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +9807957 System.Web.UI.Control.OnInit(EventArgs e) +92 System.Web.UI.Page.OnInit(EventArgs e) +12 System.Web.UI.Control.InitRecursive(控件命名容器)+134 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +489

完整代码如下:

public static List<DataTable> ListTable = new data().GetTable();
public static List<string> SallesList = new data().SallesListCreation(ListTable[0]);

//DataTable dt = new data().
public static int Load_Counter = 0;
List<Button> allControlsButton = new List<Button>();
public static List<LinkButton> allControlsLinkButtonSalles = new List<LinkButton>();

List<LinkButton> allControlsLinkButtonAffichages = new List<LinkButton>();
List<LinkButton> allControlsLinkButtonSemaine = new List<LinkButton>();

protected void Page_Load(object sender, EventArgs e)
{
    literal2.Text += "<br /> counter : " + Load_Counter.ToString();
    DateTime today = DateTime.Now;
    string sToday = DateTime.Now.ToString("dd/MM/yyyy");
    string finDate = today.AddDays(+6).ToString("dd/MM/yyyy");
    literaltest.Text = "Semaine du " + sToday + " au " + finDate;

    PlaceHolder1.Controls.Add(new LiteralControl("<br /><br /><br /> kyofu<br /><br />"));

    foreach (string sallesel in SallesList)
    {
        PlaceHolder1.Controls.Add(CreateLinkButton(sallesel + "lkbtn", sallesel, "linkButtonSalle"));
    }

    Page_init();
}

protected void Page_init()
{
    List<LinkButton> allControlsLinkButton = new List<LinkButton>();
    GetControlList<LinkButton>(Page.Controls, allControlsLinkButton);
    DateTime today = DateTime.Now;
    string sToday = DateTime.Now.ToString("dd/MM/yyyy");

    // the list of controllers is filled
    foreach (var childControl in allControlsLinkButton)
    {
        if (childControl.CssClass == "linkButtonSalleActive" ||  childControl.CssClass == "linkButtonSalle")
        {
            allControlsLinkButtonSalles.Add(childControl);
            literal2.Text += " allControlsLinkButtonSalles " + childControl.Text;
        }

        if (childControl.CssClass == "linkButtonAffichage" ||  childControl.CssClass == "linkButtonAffichageActive")
        {
            allControlsLinkButtonAffichages.Add(childControl);
        }
        if (childControl.CssClass == "linkButtonSemaine" || childControl.CssClass == "linkButtonSemaineActive")
        {
            allControlsLinkButtonSemaine.Add(childControl);
            SemaineSync(childControl);
        }
    }
    literal2.Text += " taille " + allControlsLinkButtonSalles.Count();
    //literal2.Text += " Text " + allControlsLinkButtonSalles[1].Text;

    foreach (LinkButton value in allControlsLinkButtonSalles)
    {
        literal2.Text += " <br /> Text " + value.Text;
    }

    literal2.Text += " First " + allControlsLinkButtonSalles.First().Text;
    ListFilmsBySalle(SallesList[0]);
}

private void GetControlList<T>(ControlCollection controlCollection, List<T> resultCollection)
where T : Control
{
    foreach (Control control in controlCollection)
    {
        //if (control.GetType() == typeof(T))
        if (control is T) // This is cleaner
            resultCollection.Add((T)control);

        if (control.HasControls())
            GetControlList(control.Controls, resultCollection);
    }
}

【问题讨论】:

  • 除了错误显示堆栈跟踪。
  • 了解您尝试访问列表的位置非常重要。
  • 请看更新的消息,我尝试添加元素后立即访问。
  • 我不懂法语。
  • 总结起来就是序列中没有元素。

标签: c# html asp.net


【解决方案1】:

您没有正确使用静态关键字。 静态变量,属于类本身,不属于当前实例。

尝试使用:

   public List<LinkButton> allControlsLinkButtonSalles
   {
       get
       {
           if(Session["allControlsLinkButtonSalles"] == null)
               Session["allControlsLinkButtonSalles"] = new List<LinkButton>();
           return (List<LinkButton>) Session["allControlsLinkButtonSalles"];

       }
       set
       {
           Session["allControlsLinkButtonSalles"] = value;
       }
   }

要寻找的另一个问题是,实际上有东西进入了列表,尝试调试它。

【讨论】:

  • 它告诉我session 不存在。
  • 应该是Session,大写为S
  • if(Session["allControlsLinkButtonSalles"]) 出现错误,告诉我无法在 bool 中转换对象类型。
  • 尝试在页面加载时进行,控件在页面初始化中初始化,它可能仍然为空。
  • 好吧,一个解决方法是我将allControlsLinkButtonSalles 作为参数传递给 Page_init()。所以我想你的解决方案也可以工作(暂时无法测试)。但它并没有真正告诉我为什么不能将它用作全局变量。在与链接按钮相关的函数中,allControlsLinkButtonSalles 确实有效,但仅对 Page_Init() 无效。
【解决方案2】:
Create a Static Class and Create some Attributes and Set your Values to those     

Attributes their Whenever you Want you can take it from their if Data has any change 

Again set those attributes so that you will get your data from the Class

Public static class Helper
     {
        public string SOMEPROPERTY
          {
             get;
             set;
          }
              .
              .
              .

        public List<LinkButton> SOMEPROPERTY
          {
             get;
             set;
          }


      }              

【讨论】:

  • 我明白了,我试试看。
【解决方案3】:

一开始遇到和你一样的错误,意识到我在你正在查看的 List 中没有控件,因为我没有任何一个类的 LinkBut​​ton正在搜索 allControlsLinkBut​​tonSalles 列表。

我在页面上的所有 LinkBut​​ton 上添加了 ""linkBut​​tonSalleActive"" 的 CssClass,但没有出现调试错误。

在没有 Salle 特定链接的情况下添加检查列表实际上是空的,并且您应该没有任何问题。

这是我使用的示例代码:

默认.aspx

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label runat="server" id="literal2" /> <br />
        <asp:Label runat="server" id="literaltest" /> <br />
        <asp:LinkButton runat="server" CssClass="linkButtonSalleActive" text="1"/>
        <asp:LinkButton runat="server" CssClass="linkButtonSalleActive" text="2"/>
        <asp:LinkButton runat="server" CssClass="linkButtonSalleActive" text="3"/>
        <asp:LinkButton runat="server" CssClass="linkButtonSalleActive" text="4"/>
    </div>
    </form>
</body>
</html>

Default.aspx.cs(修改版你的完整代码)

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        //DataTable dt = new data().
        public static int Load_Counter = 0;
        List<Button> allControlsButton = new List<Button>();
        public static List<LinkButton> allControlsLinkButtonSalles = new List<LinkButton>();

        List<LinkButton> allControlsLinkButtonAffichages = new List<LinkButton>();
        List<LinkButton> allControlsLinkButtonSemaine = new List<LinkButton>();

        protected void Page_Load(object sender, EventArgs e)
        {
            literal2.Text += "<br /> counter : " + Load_Counter.ToString();
            DateTime today = DateTime.Now;
            string sToday = DateTime.Now.ToString("dd/MM/yyyy");
            string finDate = today.AddDays(+6).ToString("dd/MM/yyyy");
            literaltest.Text = "Semaine du " + sToday + " au " + finDate;

            //PlaceHolder1.Controls.Add(new LiteralControl("<br /><br /><br /> kyofu<br /><br />"));

            //foreach (string sallesel in SallesList)
            //{
            //    PlaceHolder1.Controls.Add(CreateLinkButton(sallesel + "lkbtn", sallesel, "linkButtonSalle"));
            //}

            Page_init();
        }

        protected void Page_init()
        {
            List<LinkButton> allControlsLinkButton = new List<LinkButton>();
            GetControlList<LinkButton>(Page.Controls, allControlsLinkButton);
            DateTime today = DateTime.Now;
            string sToday = DateTime.Now.ToString("dd/MM/yyyy");

            // the list of controllers is filled
            foreach (var childControl in allControlsLinkButton)
            {
                if (childControl.CssClass == "linkButtonSalleActive" || childControl.CssClass == "linkButtonSalle")
                {
                    allControlsLinkButtonSalles.Add(childControl);
                    literal2.Text += " allControlsLinkButtonSalles " + childControl.Text;
                }

                if (childControl.CssClass == "linkButtonAffichage" || childControl.CssClass == "linkButtonAffichageActive")
                {
                    allControlsLinkButtonAffichages.Add(childControl);
                }
                if (childControl.CssClass == "linkButtonSemaine" || childControl.CssClass == "linkButtonSemaineActive")
                {
                    allControlsLinkButtonSemaine.Add(childControl);
                    //SemaineSync(childControl);
                }
            }
            literal2.Text += " taille " + allControlsLinkButtonSalles.Count();
            //literal2.Text += " Text " + allControlsLinkButtonSalles[1].Text;

            foreach (LinkButton value in allControlsLinkButtonSalles)
            {
                literal2.Text += " <br /> Text " + value.Text;
            }

            /*
             * CHANGES HERE
             */

            literal2.Text += allControlsLinkButtonSalles.Count > 0 ?
                " First " + allControlsLinkButtonSalles.First().Text :
                String.Empty;
            //ListFilmsBySalle(SallesList[0]);
        }

        private void GetControlList<T>(ControlCollection controlCollection, List<T> resultCollection)
        where T : Control
        {
            foreach (Control control in controlCollection)
            {
                //if (control.GetType() == typeof(T))
                if (control is T) // This is cleaner
                    resultCollection.Add((T)control);

                if (control.HasControls())
                    GetControlList(control.Controls, resultCollection);
            }
        }
    }
}

【讨论】:

  • 感谢您的回答,但我不能真正手动添加链接按钮,因为我事先不知道会有多少。
【解决方案4】:

根据您的代码值到列表allControlsLinkButtonSalles 仅在childControl.CssClass == "linkButtonSalleActive" 时添加,

我确信没有任何附加值,请查看literal2.Text 的内容:- literal2.Text += " taille "+ allControlsLinkButtonSalles .Count();

您不应该在页面上使用静态变量或属性,除非您有正当理由这样做。

【讨论】:

  • 感谢您尝试帮助我,不幸的是我无法再测试了,我完全更改了代码。正如建议的那样,我不再使用静态变量了。但我确实记得做过FirstOrDefault,但也没有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-31
  • 1970-01-01
  • 2012-02-22
  • 2014-02-12
  • 2016-05-12
相关资源
最近更新 更多