How to access on of the Control in Page from the UserControl?
How do I access the Control (dropdownlist) in current Page from the UserControl?
In the UserControl:
String test = ((DropDownList)this.Parent.FindControl("drpdwnlstMainRegion")).SelectedValue;
or
String test = ((DropDownList)this.Page.FindControl("drpdwnlstMainRegion")).SelectedValue;
It return null on ((DropDownList)this.Parent.FindControl("drpdwnlstMainRegion")) for some reason?!?!
BTW ... I am using ASP.NET C# 3.开发者_开发知识库5.
Thanks
Depending upon the structure of your page and the nesting of the controls, you may have to recursively crawl through all of the controls. Something like the following may be helpful: http://stevesmithblog.com/blog/recursive-findcontrol/
Compile these extension methods into your assembly:
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;
}
}
And then use like this:
Control whatYoureLookingFor = Page.Master.FindControlRecursive("theIdYouAreLookingFor");
This is a duplicate of a couple of questions already on SO but I couldn't find them.
精彩评论