[英]ASP.NET Accessing controls from a MasterPage using only an instance of it
我有一組包含不同過濾器的三個MasterPages,其中包含下拉列表。 在頁面中我希望使用App_Code文件夾中的幫助類來填充這些下拉列表,以減少重復的代碼。 我遇到的問題是我無法在MasterPage中找到以下方法收到的這些下拉列表。 可以這樣做還是我應該探索其他選擇?
我試圖先找到ContentPlaceHolder然后搜索但找不到下拉列表中的ContentPlaceHolder。
我也嘗試訪問父母,並從那里找到ContentPlaceHolder但沒有骰子。
其他選項是將下拉列表發送到此類並填充它們,這是更容易的解決方案。 但我想首先探討這個非常普遍的解決方案。
public static void FillFilters(MasterPage page) {
DropDownList[] dropdowns = new DropDownList[3];
dropdowns[0] = (DropDownList)page.FindControl("StatusDropDown");
dropdowns[1] = (DropDownList)page.FindControl("DepartmentDropDown");
dropdowns[2] = (DropDownList)page.FindControl("EmployeeDropDown");
...code filling the dropdowns etc. etc.
試試這個擴展方法。 您不需要MasterPage,只需要控件應該是當前控件的父級
public static class ControlsExtensionMethods
{
public static Control FindControlRecursive(this Control root, string id)
{
if (id == string.Empty)
{
return null;
}
if (root.ID == id)
{
return root;
}
foreach (Control nestedControl in root.Controls)
{
Control foundedControlInNested = FindControlRecursive(nestedControl, id);
if (foundedControlInNested != null)
{
return foundedControlInNested;
}
}
return null;
}
}
要添加到Juan答案(也許這應該是一個編輯?)我決定在我的最終代碼中使用以下內容:
public static void FillFilters(MasterPage page) {
Control parent = page.Controls[0];
DropDownList[] dropdowns = new DropDownList[3];
dropdowns[0] = (DropDownList)parent.FindControlRecursive("StatusDropDown");
dropdowns[1] = (DropDownList)parent.FindControlRecursive("DepartmentDropDown");
dropdowns[2] = (DropDownList)parent.FindControlRecursive("EmployeeDropDown");
因為我以后在方法中使用MasterPage。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.