Как я получаю доступ к Управлению (dropdownlist) на текущей Странице от UserControl?
В UserControl:
String test = ((DropDownList)this.Parent.FindControl("drpdwnlstMainRegion")).SelectedValue;
или
String test = ((DropDownList)this.Page.FindControl("drpdwnlstMainRegion")).SelectedValue;
Это возвращает пустой указатель на ((DropDownList) это. Родитель. FindControl ("drpdwnlstMainRegion")) по некоторым причинам?!?!
BTW... Я использую ASP.NET C# 3.5.
Спасибо
В зависимости от структуры вашей страницы и вложенности элементов управления вам может потребоваться рекурсивный обход всех элементов управления. Может оказаться полезным следующее: http://stevesmithblog.com/blog/recursive-findcontrol/
Скомпилируйте эти методы расширения в свою сборку:
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
public static class ControlExtensions
{
/// <summary>
/// Recurses through a control tree and returns an IEnumerable<Control>
/// containing all Controls from the control tree
/// </summary>
/// <returns>an IEnumerable<Control></returns>
public static IEnumerable<Control> FindAllControls(this Control control)
{
yield return control;
foreach (Control child in control.Controls)
foreach (Control all in child.FindAllControls())
yield return all;
}
/// <summary>
/// Recurses through a control tree and finds a control with
/// the ID specified
/// </summary>
/// <param name="control">The current object</param>
/// <param name="id">The ID of the control to locate</param>
/// <returns>A control of null if more than one control is found with a matching ID</returns>
public static Control FindControlRecursive(this Control control, string id)
{
var controls = from c in control.FindAllControls()
where c.ID == id
select c;
if (controls.Count() == 1)
return controls.First();
return null;
}
}
А затем используйте вот так:
Control whatYoureLookingFor = Page.Master.FindControlRecursive("theIdYouAreLookingFor");
Это дубликат пары вопросов, уже задаваемых SO, но я не смог их найти.