johna
johna

Reputation: 10752

Variable populated in Page_Init but null in DropDownList SelectedIndexChanged event handler

Every page request, even postback, I populate a variable in the Page_Init event, but it is null when needed in the DropDownList SelectedIndexChanged event (in the same request).

My code behind (user control) looks like this...

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

My event handler code is simple...

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

If I move the code to the Page_Load event it works okay and _offerings has the right values in the DropDown handler, but my other code doesn't work as some controls need to be repopulated in Page_Init so they are there when the postback data is populated by ASP.NET.

Note that I populate the List variable every postback as I don't want to persist it.

Upvotes: 0

Views: 233

Answers (1)

Igor
Igor

Reputation: 15893

Remove List<CRS_vwCourse2> from

List<CRS_vwCourse2> _offerings = (my query here).ToList();

You are declaring local variable _offerings inside Page_Init and the class member _offerings stays unassigned.

Upvotes: 2

Related Questions