2010-06-08 8 views
1

Comment accéder au contrôle (liste déroulante) de la page en cours à partir de UserControl?Comment accéder au contrôle dans Page à partir du UserControl?

Dans le UserControl:

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

ou

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

Il retourne null sur ((DropDownList) this.Parent.FindControl ("drpdwnlstMainRegion")) pour une raison quelconque?!?!

BTW ... J'utilise ASP.NET C# 3.5.

Merci

Répondre

1

compiler ces méthodes d'extension dans votre assemblage:

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; 
    } 
} 

Et puis utiliser comme ceci:

Control whatYoureLookingFor = Page.Master.FindControlRecursive("theIdYouAreLookingFor"); 

C'est un double de deux ou trois questions déjà sur SO mais je ne pouvais pas les trouver.

Questions connexes