Can I use parent(web page) property in web user control? - c#

How can I use parent(web page) property in web user control?
One more question:- How can I access the shared class(i.e. class in App_Code folder) property in web user control.
Thanks

You can use this.Page in asp.net user control to refer to page and it will always give you page in which that control is added.
You can access any public class declared in App_code folder directly in any user control without problem. Be careful of namespace and make sure to compile your project if you are having issues to access the class.

You could but I am not sure it would be a clean / full OOP approach, how about setting a public property or calling a public method of your user control from the page passing to it the value you need to use in the control?
this because the page hosting the control should be generic and is the page which contains the control not the other way round.
If this does not fit you, then you can take the control's Page property and cast it to the class of your page then you will be able to access its property but this will make your control specific instead of generic and it will only work when the control is hosted in pages of that exact type/class.

You have to mark the property as Public.
var myVar = ((ParentPageClass)this.Page).YourProperty;
To access the shared class you have to specify the namespace of that class:
YourProject.SomeNamespace.YourClass
or to include the namespace in your .ascx.cs file
using YourProject.SomeNamespace;
It's a cleaner aproach to pass the parameter to the user control from the parent page.

Related

Issue Related to Creating an Object of one User Control into Another

I have an asp.net Application i have added some .aspx pages in the root directory.. now i have created folder named usercontrols having following structure :
now i want to call a Method of one user control into another.. but i dont get the class name of any user controls in between..
i have used same namespace in all .ascx.cs file..
so how to call a Method of one user control into another ??
Thanks
You need a reference declaration to use the uc within your code:
Add it to your page:
<%# Reference Control ="~/WebUserControl1.ascx"%>

Accessing a master page public variable from user control

public partial class MasterPages_Main : System.Web.UI.MasterPage
{
public LoggedInUser ThisUser;
This is in my master page, and my user control is running on the page. In my user control however, I can't seem to reference ThisUser, do I have to pass it in to the control as a parameter? Is there any way to directly reference it?
Absolutely! Take a look at the methods and properties of an asp.net page. I've done similiar using:
HtmlForm mainform = (HtmlForm)Master.FindControl("form1");
Where the important part is the Master.FindControl();
This is a part of the Page class. Page.Master will get you to the master page of the current page.
I'm sure that there's some way to avoid passing an instance of LoggedInUser to your control, however it's probably best to pass it as a parameter as doing so promotes reuse of the control because it will be more loosely coupled.

asp.net Cannot create UserControl in class

My ultimate goal is to create a UserControl in a class in my App_Code folder and render the html from that into a string.
The rending of HTML can be done using this example I believe:
How do I get the HTML output of a UserControl in .NET (C#)?
My Question:
I created my user control
public partial class Controls_MyUserControl : System.Web.UI.UserControl
I've registered it in my web.config
<add tagPrefix="UC" src="~/Controls/MyUserControl.ascx" tagName="MyUserControl" />
I can reference this on a page just fine
<UC:MyUserControl ID="MyUserControl1" runat="server" />
Yet when I try to create an object of this control type in a class (in my app_code folder) it doesn't allow me.
Controls_MyUserControl dummy = new Controls_MyUserControl();
The potentially strange thing is when I put this code into a code behind of a page, it works.
Any ideas on what I need to do to have the usercontrol to be able to be created in my class in the app_code folder?
My guess is, is that I need to reference the control in a "using" statement at the top, but I'm not sure what that'd be.
It's not in a namespace to my knowledge (at least there's no namespace, in the code behind of the actually user controls). Though I'm not sure if it inherits one from the System.Web.UI.UserControl.
Thanks in advance
Some workaround as posted by Scott Alen http://www.velocityreviews.com/forums/t119801-accessing-web-user-control-from-class-in-app_code-folder.html
Suppose you have all your user controls in ~/UserControls/
Then on your code behind add the following;
using YourSpaceName.UserControls;
This will set reference to any user control in that location.
Note: if you are using a user control within another, make sure to create a folder for each of them. I have experiencing problems, specifically with VB where it would compile but give me a runtime error. Since I encounter that problem I create my user controls each in it's own folder.

Web Control added in .master control type not found in child page

I have a Web Site project, and within it I have a user Web Control defined in an ascx file.
The control is added to the Site.Master, and it shows up correctly on the page and everything is fine.
I need to override some of the control's fields on one of the pages that derive from Site.Master.
// In OnLoad:
MyControlName control = (MyControlName) Page.Master.GetBaseMasterPage().FindControl("controlID"));
The issue is that MyControlName doesn't register as a valid Type on the child page. If I add a second instance of the control to the child page directly, the above works as needed, but if the control isn't placed directly on the page, and instead is only defined in the master page, the type is undefined. The control is not in a namespace, and is defined within the project, so I don't know why it is having such an issue location the appropriate type.
If I put a breakpoint in the OnLoad, the type listed for the control is ASP.my_control_name_ascx, but using that does not work either.
Why can't the child class reference the correct type? Can I fix this?
Thanks!
The control does not have global scope over the entire project. It will only be selectable as a type on pages where the control is registered. So you have to register the control on the child page:
<%# Register src="WebUserControl.ascx" tagname="WebUserControl" tagprefix="uc1" %>
You will need to add a register tag like above to the top of your child aspx page.
The other option is you could create an interface for the control which exposes the properties or methods you want to access, and put the interface in app_code or some other globally accessible place, then have the control implement the interface, and cast the control to the interface.
The following code works for me:
DropDownList ddlLanguage = (DropDownList)Page.Master.FindControl("ddlLanguage");
I take it GetBaseMasterPage() is your own method? What happens if you try:
MyControlName control = (MyControlName)Page.Master.FindControl("controlId");
?
Not a direct answer to your question, but you might find the #MasterType directive useful.
If you add a line like
<%# MasterType TypeName="ClientName.SiteName.MasterPages.SiteMaster" %>
to the top of your ASPX page, you should be able to refer to the master page in code without having to cast it. This might make it easier for the code to find your control, perhaps?
You could end up with a line like:
// In Page.OnLoad:
MyControlName control = Page.Master.MyControl;
and then expose a new property in your master page that wraps the FindControl call:
// In Site.master.cs
internal MyControlName MyControl
{
get { this.FindControl("controlID"); }
}
Hope this helps!

Failing to add controls to a page dynamically

I'm adding a User Control for each record pulled up in a data reader, here's the basic loop:
while (dr.Read())
{
ImageSelect imgSel = new ImageSelect(dr["Name"].ToString());
myPanel.Controls.Add(imgSel);
}
The problem is that there are no controls added to the page, I check the html output and there is my panel, with nothing in it.
I even stepped through the code in the debugger, and verified that myPanel.Controls gets a control added on each loop, with the count being 6, no errors, but then they dont show up on the page.
I've run the above code in the Page_Init and Page_Load events, both with the same result.
EDIT:
Ok so I've switched to using LoadControl("....ascx") to get my control instance, which is now working. But originally I was also passing in data via the controls constructor.. Is this still possible or do I just need to set them via get/sets?
EDIT 2:
Thanks to Freddy for pointing out that the LoadControl has an overload where you CAN pass in constructor params, see accepted answer.
EDIT 3:
After trying this method both with and without the constructor. I have found its better to just use setters for any properties I want the control to have versus trying to use the passed in object array for my constructor.
Update: As Steve pointed out, the overload of LoadControl that uses the type won't take into account the controls in the ascx. This is also mentioned in this answer: Dynamically Loading a UserControl with LoadControl Method (Type, object[]).
As I mentioned before, the get/set are more in line with the asp.net model, so I recommend using that with the LoadControl variation that receives the user control path. That said, the Steve's version is an interesting alternative: http://www.grumpydev.com/2009/01/05/passing-parameters-using-loadcontrol/.
My take is the LoadControl with type is meant to be used with web custom controls instead.
If it is an user control you should use LoadControl(usercontrolpath) to get the instance of the user control.
You can use a constructor by doing:
var name = dr["Name"].ToString();
var imgSel = LoadControl(typeof(ImageSelect), new object[]{ name });
myPanel.Controls.Add(imgSel);
Notice that depending on the project model you are using, you need to add a Reference to the aspx to use it with the typeof variation:
<%# Reference Control="~/somepath/myusercontrol.ascx" %>
Ps. I usually use the set/get for controls as I find them more in line with the asp.net model
To add UserControls you must call the LoadControl method passing in the path to the .ascx file. You can not create them by just instantiating the object the .ascx file inherits from.
A UserControl consists of both the markup and the class in the code behind. The markup contains a link to the class behind, but the class behind does not know where the markup lives and therefore can not be created on it's own.

Categories