Print Page | Close Window

Finding a control in codebehind.

Printed From: Web Wiz Forums
Category: General Discussion
Forum Name: ASP.NET Discussion
Forum Description: Discussion and chat on ASP.NET related topics.
URL: https://forums.webwiz.net/forum_posts.asp?TID=16287
Printed Date: 29 March 2026 at 8:34pm
Software Version: Web Wiz Forums 12.08 - https://www.webwizforums.com


Topic: Finding a control in codebehind.
Posted By: Leeb65
Subject: Finding a control in codebehind.
Date Posted: 22 August 2005 at 8:23am
Hi all,
 
not sure how often this question has been answered, if at all. 
 
I have written a webcustomcontrol (NOT ascx). 

I have 10 on a web page and want to find them  in the code behind.

I have tried using foreach, but I am not sure what  collection to search in. 

Does anyone know the answer to this question? Is it possible?

Thanks in advance,


-------------
Lee

http://www.rheinsitemedia.de">



Replies:
Posted By: Mart
Date Posted: 22 August 2005 at 9:34am
foreach (Control c in this.Controls)
{
if (c.GetType() == typeof(YourControl))
{
Response.Write(c.Name);
}
}


Posted By: Leeb65
Date Posted: 23 August 2005 at 7:46am

I get this error:

Object does not match target type.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Reflection.TargetException: Object does not match target type.

Source Error:

Line 71: 						if(y.Name == "EditMode")
Line 72: 						{
Line 73: 							y.SetValue("EditMode", bEdit, null);
Line 74: 						}
Line 75: 					}

Source File: d:\www\smdtest\default.aspx.cs    Line: 73
 
From this code:
 

Type t;

foreach (Control oPart in this.Controls)

{

t = typeof(SMDCMS.WebPart);

if (t.FullName.IndexOf("WebPart")>0)

{

PropertyInfo[] p = t.GetProperties();

foreach(PropertyInfo y in p)

{

if(y.Name == "EditMode")

{

y.SetValue("EditMode", bEdit, null);

}

}

}

}

 
Please help!!
 


-------------
Lee

http://www.rheinsitemedia.de">


Posted By: Mart
Date Posted: 23 August 2005 at 10:17am
much more compact and doesn't use reflection (NEVER use reflection in a loop like that just to set properties - it is as slow as hell). Just use boxing to convert the type


foreach (Control oPart in this.Controls)
{
    if (oPart.GetType() == typeof(SMDCMS.WebPart))
    {
        SMDCMS.WebPart webPart = oPart as SMDCMS.WebPart;

        webPart.EditMode = true;
    }
}




Print Page | Close Window

Forum Software by Web Wiz Forums® version 12.08 - https://www.webwizforums.com
Copyright ©2001-2026 Web Wiz Ltd. - https://www.webwiz.net