Home » C# Programming

Using reflection in a user control

I would like to use reflection to set a property of another control on the form from the user control I am building (ie. set the ImageIndex of another button from my user control). Can anyone give me an idea on how to do this?




6 Answers Found


Answer 1

I'm sorry it's not quite clear what you're asking. Do you want to change the property  of another control  while your builing a user  control OR do you want to build a control that when the user interacts with it it changes the properties of another control?


Answer 2

Why do you think you need to use reflection?

Answer 3

I would like to do the second. When the user  interacts with the user contro at runtime it changes a property  (specifically the ImageIndex) of other controls (more than 1). I am assuming I need to use reflection  to set  the properties of the other controls as I have not found a way to make a property in my user control  that stores a collection of object references of the other controls.

If there is a better way of accomplishing this please enlighten me :-)


Answer 4

See reply to Pantelis4499. Thanks

Answer 5

What is that collection of controls you want to change? All the controls? Controls from a list of names?

- TopLevelControl.Controls retrieves all controls on the form.

- TopLevelControl.Controls.Find(name, true) retrieves all controls with a specific name.

You can then cast the control  to whichever type you need and set  its ImageIndex to the value you want.

If you want to set the ImageIndex property  but you don't know the type of the control, you can use reflection  on the controls retrieved:

control.GetType().GetProperty("ImageIndex").SetValue(control, value, null);


Answer 6

This is exactly what I was looking for! Thanks a bunch.




I have Control A and on Control A is control B.

From Control B i need to access and set the value of a label on Control A but I keep getting "Object not set to an instance of an object"

I have accessed controls before from other controls but this is the first time I have had to do it when the second control is actually ON the first control?


I have a Page containing two user controls and one user control contains more 2 controls i.e


My page is Page1 and  it contains two user controls UC1A & UC1B

More the UC1B Contains more two User Controls consider Name them UC1BA

And UC1BB now I have 3 text boxes and a dropdown list in UC1BA whose values I need for processing some grids in UC1BB how can I get the selectedvalue of dropdown and Text of text boxes.


Hello All,

I have a requirement where i need to access the methods of one user control in another user control.
Any pointers in this direction is greatly appreciated.

Thank you


Is it possible to inherit a Windows User Control in WPF User Control. I mean a WinForms User control as a base class to a WPF User Control class (which would be of Xaml). Please let me know the steps or code snippet.

Thanks in advance.


Hi ,

I have user control, which get call on <id href>

i am setting some value on user control on prerender, so i can see value which selected 1st time, but when i re chnage value and again open pop up screen not see changed value.

even i can see from code behind my value setting correctly, and passing correctly on aspx page , but look like not reassing value


user contrl on aspx page:








below partial code 

user control:












<paramname="initParams"value="wxLat=<%=_wxLat %>,wxLng=<%=_wxLng %>,clientId=110001001,defZoom=7,multiLayerSupport=false,defLayer=<%=_defLayer %>,layerList=<%= _layerList%>"/>






<imgsrc="http://go.microsoft.com/fwlink/?LinkId=161376"alt="Get Microsoft Silverlight"style="border-style:none"/>







I've created a custom control, however, as a direct "Forms.UserControl" I can't seem to be able to "add" child controls to it.  So I've inherited from Panel instead, which worked, however, I'm adding controls to the "Panel" not to the "GroupBox" contained within the User Control. 


How would I (Using Panel or UserControl as the Parent Class for Inheritance) add a GroupBox to the control, and subsequently allow the Forms designer to add a Control (like a checkbox) to the GroupBox control contained within Me.Controls for the custom control?

Basically, I drop UserGroupBox1 onto the form, and then on the same form drop a CheckBOx1 onto the UserGroupBox1 which adds it to the GroupBox contained within.  How do i do that in the UserGroupBox1 control creation?


Jaeden "Sifo Dyas"

I have a 32-bit runtime running on my target. If I go to Control Panel -> User Accounts, I get one icon called Credential Manager. I don't get the options to Change account name, passwords etc. Any suggestions? I can post the answer file if anyone would like to take a look at it.

I have a application which uses webparts and 1 control is also a Script Control.

So my user controls are derived from System.Web.UI.WebControls.WebParts.WebPart which makes them webparts.

I have everything setup and working fine as far as the personalization and webpart goes... every thing displays and works fine.

Except that 1 of my control needs to do a bit of work in the OnPreRender event and it turns out that event only gets fired when a user is loged in the application.

That control is also a script control so it inherits from System.Web.UI.WebControls.WebParts and also implement IScriptControl

So lets imagine that an administrator while logged in switched to 'Sharedscope' within the webpartmanager and then has added the usercontrol/webpart 'calendar' to the top webpart zone. This then makes the 'calendar' control viewable by all and any user who visits the page wheter logged in or anonymous.

And this works fine and very well as it is supposed to. However in the 'Calendar' user control which is derived from System.Web.UI.WebControls.WebParts I have an overiden 'OnPreRender' event like this:

Protected Overrides Sub OnPreRender(ByVal e As EventArgs)

If Not Me.DesignMode Then

Me.isloaded = True

' Test for ScriptManager and register if it exists

sm = ScriptManager.GetCurrent(Page)

If sm Is Nothing Then _

Throw New HttpException("A ScriptManager control must exist on the current page.")


End If


End Sub


And this, it turns out..... only gets fired when a user is logged in. and after further testing I found out that the same is true for the 'CreateChildControls' event...



I'm trying to create a user control that contains a group of controls.  To begin with (and to remove as much complexity as possible) I am trying to create a relatively simple solution with a user control that contains a group of TextBox controls (see below).  The problem is though, that although I can update my _testList variable during design time after adding my RowTest control to a form nothing actually happens, no new TextBox is drawn or anything.  I am relatively new to this whole idea so I'm not sure where I am going wrong, any clues?  Even if someone could just point me in the direction of an example I could emulate that would be great.



using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

using ListViewTest;

namespace RowTest
 public partial class RowTest : UserControl
  List<TextBox> _testList = new List<TextBox>();

  public RowTest()

  public List<TextBox> TextBoxList
    return _testList;

    _testList = value;


Which one is better? i feel custom control is lighter than user control


1how to acess controls in usercontrol  in javascript function where user control hosted in webpart


2)How to retieve values from javscript code to server side

details as follows

StringBuilder controlString = new StringBuilder();
            controlString.Append("<p>" + CurrentPage.ToString() + "of " + TotalPages.ToString() + " </p>");
            for (int intIndex = 1; intIndex <= TotalPages; intIndex++)
                controlString.Append("<li><a href='#' id='" + intIndex.ToString() + " '  onclick=javascript:GetNumber(this.id)>" + intIndex.ToString() + "</a></li>");   --  Here i called javascript function
            controlString.Append("<div class='dbfl'><a class='nextPages' title='Go to next page' href='#'>&nbsp;</a></div>");
            controlString.Append("</div>");  in usercontrol

in code behind



When i actually call this function in usercontol hosted in webpart

1)In javascript function, hidden field <asp:HiddenField ID="hdn" runat="server" /> in user control .ascx

is not acessible

/var txtBox = document.getElementbyId('<%=hdn.ClientID%>')
id='ctl00_m_g_3c5f56de_9f0d_4734_917e_438f1237e7f8_ctl00_hdn' -- This id is generated
document.getElementbyId(id).value=id--javascript thows error  for not valid propery



2)though value defined in stringbuilder is accessible 

 controlString.Append(" <input type='hidden'  id='hdnNumber'  value=''  runat='server'/>");

this value can not be retrieved back in server side code from javascript

document.getElementById('hdnNumber').value=id // This is valid for javascript function but,Its value can not be retrieved back in server side code


Its able to access

function GetNumber(id)
//var txtBox = document.getElementbyId('<%=hdn.ClientID%>')



So I have a user control with a split container in it. I have the properties set up to allow access to the split containers properties when working with the User Control. The problem is that the user of the user control can null out and change the split Container itself, I want to restrict them from doing that. (Like a panel in a split Container).

I have a composite control (Called Dialog) which has a property "ContentControl"

At design time, I'd like this property to bind to a user control that is on the page.

When I add the items in the designer, the designer loads as expected.

However, when I try to run the web page, I get the following error:

Parser Error Message: Cannot create an object of type 'System.Web.UI.UserControl' from its string representation 'EditTerm1' for the 'ContentControl' property.

Please let me know if there is another way to bind a user control as a property of a composite control.


Designer Code:


	<cc1:Dialog ID="Dialog1" runat="server" Buttons="SaveCancel" 
Title="Edit Term" ContentControl="EditTerm1" />

<uc1:EditTerm ID="EditTerm1" runat="server" />


Dear guy,

i am very new to asp.net and i am trying to make a pop-up messsage box, using popupControlExtender. Such extender will be inside a web user control but the target control will be outside the user control instead. Could anyone tell me how i can do it ? 


my user Control : UCPopUp.ascx

<asp:Panel ID="pnlPopUp" runat="server" style="display:none" >

<div class="clsPopUp" >

<asp:Literal ID="lblPopUp" runat="server" Text="Pop up Message." />



<asp:PopupControlExtender ID="PCEPopUp" runat="server"                                                     

TargetControlID="TxtMyControl" PopupControlID="pnlPopUp"  Position="Right" /> 


in the page,

<asp:textbox id="txtMyControl" runat="server" text="" />

<uc1:UCPopUp id="ucPopUp1" runat="server" />




Thanks guys !!!!

                                                <asp:Panel ID="pnlPassword" runat="server" style="display:none" >
                                                    <div style="width:100px; margin: 0px 0px 0px 10px;">
                                                    <asp:Literal ID="lblPopPassword" runat="server" Text="Please enter the Password you've chosen." />
                                                <asp:PopupControlExtender ID="PCEPassword" runat="server"                                                     
                                                    TargetControlID="Password" PopupControlID="pnlPassword"  Position="Right" /> 


I have a parent .aspx page that has a asp:panel control in it, and this parent .aspx is also referencing a user control that I registered in that .aspx. Lets just call it usercontrolA.ascx for this post.

The user control has a radiobuttonlist itself.

Based on a selection from the radiotbuttonlist in the user control, I want to be able to hide the asp:panel in my .aspx (parent) but unfortunately I cant' get it to work:

parentPanel.visible = true;  <<< I trried this in usercontrolA.ascx.cs

But the user control doesn't know about the panel in the parent .aspx

So do I need to expose that somehow from the parent so that I can access it from the code behind of the child .ascx?  How?



I've created the .dll assembly with custom web controls and use it successfuly, but my last control needs a javascript. It is also in the same .dll with the control.

The problem: My project doesn't see the javascrip in the externlal assembly.

The question: How to tune the visibility of javascripts in the external assembly?

Thank you.






I have a user control (.ascx) in which I am calling web service through javascript.

For that i have to add ScriptManager control in .ascx. But if I use this control on a same page more than once, I get the exception 'Only one instance of ScriptManager control can be added on page'. This is obvoius as 'ScriptManager' control will be loaded multiple times.

So my query is : Can we add ScriptManager dynamically in .ascx by checking if its alredy exists on page?



hey there,

i have a user control that has a few inner controls like lables and images that represents a "movie".

from a web page i get a list of movies (List<Movie>) and for each movie in the list i want to generate my user control and add it to a panel.

(i added a movie type data member to the user control)

code (1):

List<Movie> movies = movieRepo.GetAllMovies();
        foreach (Movie movie in movies)
            MovieControl movieControl = new MovieControl();
            movieControl.Movie = movie;

List<Movie> movies = movieRepo.GetAllMovies();

foreach (Movie movie in movies)


    MovieControl movieControl = new MovieControl();

    movieControl.Movie = movie;




in my Movie user control i created a method that populates the movie information:

code (2):

public void PopulateMovieInfo()


        img_Movie.ImageUrl = movie.ImgURL;

        img_Movie.PostBackUrl = string.Format("AnotherPage.aspx");

        lbl_Description.Text = movie.Description;

        lbl_Director.Text = movie.Director;

        lbl_Genre.Text = movie.Genre.ToString();

        lbl_LengthInMin.Text = movie.LengthInMin.ToString();

        lbl_Title.Text = movie.Title;


when this method is called within the foreach loop, all the sub controls of the movie user control are null. why is this?

i should say that i generate all the movie controls (code 1) in the Page_Load method.


I Have a usercontrol that has a label, the content property of the label I would like to be bound from a slider in the MainWindow class, would this be done by a delegate and event or is there a binding I can apply to it in XAML?

TIA Mike



I have a table that displays a user control on each row. The user controls are strongly typed to a viewmodel which contains DataAnnotation style validation. If one of the rows has invalid data entered (lets say the 3rd row) the data annotation validates display agains the first row/user control.

How do I get the data annotation to show against the relevant user control?


<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure