【问题标题】:Variable populated in Page_Init but null in DropDownList SelectedIndexChanged event handler在 Page_Init 中填充但在 DropDownList SelectedIndexChanged 事件处理程序中为空的变量
【发布时间】:2015-01-23 04:17:10
【问题描述】:

每个页面请求,甚至回发,我都会在 Page_Init 事件中填充一个变量,但在 DropDownList SelectedIndexChanged 事件中需要时它为空(在同一个请求中)。

我背后的代码(用户控制)看起来像这样......

public partial class CourseInfoDetail : System.Web.UI.UserControl
{
  protected List<CRS_vwCourse2> _offerings;
  protected bool _test;
  protected void Page_Init(object sender, EventArgs e)
  {
     _test = true;
     using (CRSDataContext dc = new CRSDataContext(Config.ConnString))
     {
        List<CRS_vwCourse2> _offerings = (my query here).ToList();

        //code removed here, but _offering is not used for anything other than displaying data here

我的事件处理程序代码很简单...

protected void ddlLocationId_SelectedIndexChanged(object sender, EventArgs e)
{
  //_test is true here
  //_offerings is null here

如果我将代码移至 Page_Load 事件,它可以正常工作,并且 _offerings 在 DropDown 处理程序中具有正确的值,但我的其他代码不起作用,因为需要在 Page_Init 中重新填充某些控件,以便它们在回发时存在数据由 ASP.NET 填充。

请注意,我在每次回发时都会填充 List 变量,因为我不想保留它。

【问题讨论】:

    标签: asp.net webforms


    【解决方案1】:

    中删除List&lt;CRS_vwCourse2&gt;
    List<CRS_vwCourse2> _offerings = (my query here).ToList();
    

    您在 Page_Init 内声明局部变量 _offerings 并且类成员 _offerings 保持未分配状态。

    【讨论】:

    • 非常感谢。我知道我在做一些愚蠢的事情,但我看不到。我很惊讶在做这样的事情时没有显示错误。
    • @Igor 的回答确实有帮助,但前 10 分钟我无法接受……现在接受了。
    猜你喜欢
    • 2010-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多