在我創建基於數據編寫的用戶控件的新實例的頁面上工作。我使用構造函數注入將過濾的數據傳遞給用戶控件。但是,當用戶控制渲染時,僅爲所有用戶控件渲染注入的最後一組數據。看來我引用的是同一個實例,而不是創建一個新的獨立實例。想法?注入不同數據的多個用戶控件顯示相同的數據
protected void Page_Init(object sender, EventArgs e)
{
var data = <my data comes from here>;
var yearsInData = data.OrderByDescending(x=>x.Year).Select(x => x.Year).Distinct();
foreach(var year in yearsInData)
{
var employers = data.OrderBy(x=>x.EmployerName).Where(x => x.Year == year).Select(x => x.EmployerName).Distinct();
foreach (var employer in employers)
{
var eob = data.Where(x => x.Year == year).Where(x => x.EmployerName == employer);
if (eob.Count() > 0)
{
var ctl = LoadControl(@"~\Shared\Controls\AnnualEOBControl.ascx", eob);
pnlMain.Controls.Add(ctl);
}
}
}
}
這裏是LoadControl方法:
private UserControl LoadControl(string userControlPath, params object[] constructorParameters)
{
var constParamTypes = new List<Type>();
foreach (var constParam in constructorParameters)
{
constParamTypes.Add(constParam.GetType());
}
var ctl = Page.LoadControl(userControlPath) as UserControl;
// Find the relevant constructor
if (ctl != null)
{
var constructor = ctl.GetType().BaseType.GetConstructor(constParamTypes.ToArray());
// And then call the relevant constructor
if (constructor == null)
{
throw new MemberAccessException("The requested constructor was not found on : " + ctl.GetType().BaseType);
}
constructor.Invoke(ctl, constructorParameters);
}
// Finally return the fully initialized UC
return ctl;
}
它發生在我看來,它可能是一個更清潔,只是調用.ToArray()當你餵養LoadControl。同樣的效果。 – 2011-04-11 18:00:16
得到了同樣的結果。還有什麼我需要嘗試? – 2011-04-11 18:42:30
嘗試使用.ToArray()方法。我承認不是一名封閉專家,但我不能動搖這種情況。 – 2011-04-11 18:46:01