Как получить доступ на Управления на Странице от UserControl?

Как я получаю доступ к Управлению (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.

Спасибо

1
задан dcpartners 8 June 2010 в 06:00
поделиться

2 ответа

В зависимости от структуры вашей страницы и вложенности элементов управления вам может потребоваться рекурсивный обход всех элементов управления. Может оказаться полезным следующее: http://stevesmithblog.com/blog/recursive-findcontrol/

1
ответ дан 2 September 2019 в 23:58
поделиться

Скомпилируйте эти методы расширения в свою сборку:

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&lt;Control&gt;
    /// containing all Controls from the control tree
    /// </summary>
    /// <returns>an IEnumerable&lt;Control&gt;</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, но я не смог их найти.

1
ответ дан 2 September 2019 в 23:58
поделиться
Другие вопросы по тегам:

Похожие вопросы: