如何从UserControl访问Control in Page?

时间:2010-06-08 06:00:14

标签: asp.net

如何从UserControl访问当前页面中的Control(下拉列表)?

在UserControl中:

String test = ((DropDownList)this.Parent.FindControl("drpdwnlstMainRegion")).SelectedValue;

String test = ((DropDownList)this.Page.FindControl("drpdwnlstMainRegion")).SelectedValue;

由于某种原因它在((DropDownList)this.Parent.FindControl(“drpdwnlstMainRegion”))上返回null?!?!

顺便说一句......我正在使用ASP.NET C#3.5。

由于

2 个答案:

答案 0 :(得分:1)

根据页面结构和控件的嵌套,您可能必须递归遍历所有控件。以下内容可能会有所帮助:http://stevesmithblog.com/blog/recursive-findcontrol/

答案 1 :(得分:1)

将这些扩展方法编译到程序集中:

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上已经提出的几个问题的重复,但我找不到它们。