我無法想出一個好主題。我有一個簡單的ASP.NET 3.5表單。如果您遵循編號的註釋,我將解釋在調試模式下運行頁面時,我是如何跨越代碼的。下面的兩個函數都是在頁面文件後面的代碼中聲明的方法,它們都在同一個_Default類中。 ManagersListBox在Default.aspx頁面中聲明。爲什麼在GetSubordinates的上下文中,ManagersListBox是空的?就好像它消失了一會兒,然後從GetSubordinates方法返回後再次出現。顯然,解決方案是參數化GetSuborindates,但這不是我關心的問題。我想了解ASP.NET如何工作,我真的很想了解爲什麼我看到這種行爲「消失的對象」。謝謝。ListBox在ObjectDataSource的Select方法中爲null
隱藏文件<asp:ListBox ID="ManagersListBox" runat="server" Width="293px"
DataTextField="LoginID" DataSourceID="ObjectDataSource2"
DataValueField="EmployeeID" onload="ManagersListBox_Load"
AutoPostBack="true" onprerender="ManagersListBox_PreRender"></asp:ListBox>
<asp:ObjectDataSource ID="ObjectDataSource2" runat="server"
SelectMethod="GetSubordinates" TypeName="WebApplication._Default">
</asp:ObjectDataSource>
代碼:
protected void ManagersListBox_PreRender(object sender, EventArgs e)
{
if (ManagersListBox != null)
{
//1. Right here, ManagersListBox is not null
}
//2. This call causes the ObjectDataSource to call GetSubordinates
ObjectDataSource2.Select();
//4. After stepping out of GetSubordinates and back here,
// ManagersListBox is again non-null.
}
public List<DataModel.Employee> GetSubordinates()//int ManagerID)
{
//3. ManagersListBox is always null here
using (DataModel.AdventureWorksEntities entities = new DataModel.AdventureWorksEntities())
{
if (ManagersListBox != null)
{
return (from employee in entities.Employees
where employee.Manager.EmployeeID == Convert.ToInt32(ManagersListBox.SelectedValue)
select employee).ToList();
}
else
{
return (from employee in entities.Employees
select employee).ToList();
}
}
}
不是一個完整的答案,但你也可以檢查我的答案在這裏:http://stackoverflow.com/questions/32642032/wrestling-with-objectdatasource-other-controls-and-variables-not-defined/32715967#32715967 – Canavar 2015-09-22 11:45:38