문제

Working on ASP.NET app, my project need to find control from page ,use bellow syntax to find control from a page:

public static Control FindControlRecursive(Control Root, string Id)
{
    Control FoundCtl = new Control();
    if (Root.ID == Id)
        return Root;

    foreach (Control Ctl in Root.Controls)
    {
        if (FoundCtl != null && FoundCtl.ID == Id)
        {
            
            Type ty = FoundCtl.GetType();
            var r = FoundCtl as ty; 
            
            //var r = FoundCtl as  Telerik.Web.UI.RadComboBox;   
        }

        FoundCtl = FindControlRecursive(Ctl, Id);

        //if (FoundCtl != null)
        //    return FoundCtl;
    }

    return FoundCtl;
}

For retrieve control value from the control need to cast. For cast use bellow syntax

FoundCtl as TextBox;
                

Is it possible to cast find control as bellow

Type ty = FoundCtl.GetType();
var r = FoundCtl as ty;
도움이 되었습니까?

해결책 2

You cannot do this in such way. All cast operators is not work with variable of type System.Type . Moreover, if you want to work with this control in runtime with reflection, you can use reflection methods to work with it (such as PropertyInfo.SetValue etc). But usually you exatly know what type is of concrete control. Why do you want to cast in runtime?

다른 팁

The most proper way is the following:

TextBox textBox = FindControl("name") as TextBox;
if (textBox != null)
{
    // use it
}

Why doesn't it work for you?


Also you can use an extension method to find controls of given type recursively:

public static IEnumerable<Control> GetChildControls(this Control control)
{
    var children = (control.Controls != null) ? control.Controls.OfType<Control>() : Enumerable.Empty<Control>();
    return children.SelectMany(c => GetChildControls(c)).Concat(children);
}

Usage:

var textBoxex = this.GetChildControls<TextBox>();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top