2010-06-08 72 views
1

如何从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。

感谢

回答

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"); 

这几个问题的重复已经在所以但我找不到它们。

相关问题