ASP.NET Page_Load values are lagging one postback behind
I have a foreach loop in the Page_Load method of my one开发者_运维技巧 page to determine whether to Enable a button or not.
Code:
foreach (var class in classes)
{
for (var i = studentsList.Count - 1; i >= 0; i--)
{
if (studentsList[i].Id == class.student_id)
studenstList.Remove(studentsList[i]);
}
}
if (studentsList.Count == 0)
{
button1.Enabled = false;
button1.Text = "a";
}
else
{
button1.Enabled = true;
button1.Text = "b";
}
if (Page.IsPostBack) { return; }
The issue:
The value of studentsList.Count
is lagging behind by a postback. If after the loop it should be 1, it only has the value of 1 at the next postback. I've debugged to confirm this is the case.
You can move this foreach loop to the Page_PreLoad method and give it a try.
Here anof life cycle of an ASP.NET page: http://msdn.microsoft.com/en-us/library/ms178472.aspx#lifecycle_events
I guess the student list is updated by clicking a button on the page.
Put the code that enables button1 on the button_click event of that button.
Does the button press edit students list? If so, the code for the button press will be fired after the Page_Load code.
Your problem is that you should wait for a corresponding event and write this logic in that event handler. For clarity, page load happens earlier than control events.
精彩评论