How can access property of .aspx in the user control? - c#

I have an .aspx page in which I have a property. Now i create a user control and drop it on the page. Now how can i access that property in code behind of usercontrol.

The best way is to expose a public property in the UserControl and assign that property from the ASPX page:
By code:
var uc = this.myUserControl as MyCuserControlType;
uc.CustomUserControlProperty = this.MyPageProperty;
Declaratively
<uc:MyUserControlType1 runat="server= ID="myUserControl" CustomUserControlProperty="<%# this.MyPageProperty %>" />
Note: If you want to use declarative markup you would need to call this.DataBind(); in code to force the binding
Edit 1
In case you want to do the opposite (pass a value from the control to the page in response to an event) you could declare your own custom event in the user control and fire it when needed it.
Example:
User control code behind*
public event Action<string> MyCustomEvent = delegate{};
....
// somewhere in your code
this.MyCustomEvent("some vlaue to pass to the page");
Page markup
<uc:MyUserControl1 runat="server" onMyCustomEvent="handleCustomEvent" />
Page code behind
public void handleCustomEvent(string value)
{
// here on the page handle the value passed from the user control
this.myLabel.Text = value;
// which prints: "some vlaue to pass to the page"
}

If a user control needs to access something on the parent page, then maybe this user control should have included it as its own property which could be set from the parent. Ideally user controls should be independent from any parent context or other user controls on the page, otherwise they really are not something reusable. They need to be self contained and configurable throughout their the properties they are exposing.

Related

Sanity check: Master Page, Content Page and ASCX dependencies

I'd like someone to give what we're doing a glance-over and tell me whether we're going about it an odd way.
What I have:
We have a .master (Master Page), .aspx (Content Page) and an .ascx (User Control).
The User Control should appear on all pages, so we have placed it on the Master Page
The User Control should be initialised differently based on the Content Page it appears on. So, the Content Page has the resposibility of raising an event on the User Control, passing in some arguments, which initialises the control.
Questions:
In my mind, this removes any dependency between the User Control and either the Content Page or Master Page. Am I correct?
Is calling an event on the User Control the easiest way to pass arguments in and initialise the control accordingly?
Happy to clarify any further points, Thanks.
I would say that's OK, but I would like to seek a clarification: how does the user control subscribe to the event of the content page?
Alternatively, you could also consider creating an interface for the master page:
public interface IMyMaster
{
UserControlType Control { get; }
}
After applying this interface to the master, the interface can return a direct reference to the control. The content page can then do:
if (this.Page.Master is IMyMaster) {
((IMyMaster)this.Page.Master).Control.Initialize();
}
HTH.

Creating Webuser control for Sidebar dashboard with modal popUp for each item

Hi basically i want to create a Control that can add popup to menuItems which is declared in the markup of the page. I would like the syntax to be like below:
<uc1:Sidebar id="" runat="server" enablePopup="True">
<PopUpBindings>
<PopedControlId="" BackgroundClass="" TargetItemIndex=""/>
<PopedControlId="" BackgroundClass="" TargetItemIndex=""/>
..
</PopUpBindings>
</uc1:Sidebar>
I am able to create enablePopUp using Member Fields in the asmx Page. Like Below
private bool _enablePopup;
public Boolean EnablePopup
{
get { return _enablePopup; }
set { _enablePopup = value; }
}
but creating a bindings set as in markUp 1. Never done that before. Could someone give hints to this.
Question 2:
This usercontrol is being created because modalPopup could not be created along with Repeater's Databinding. I tried the below in repeaters ItemDatabound event but would throw exception "Target control Id ={0} could not be found"
mpcpnlNewBp.TargetControlID = e.Item.ID;//open modalpopup
What you need is Collection properties on your control - see this example code from MSDN to get an idea.
If more designer support such as UI for editing properties is needed then you need to create Collection Editor - check this related example.
EDIT:
With templated controls such as repeater, target control needs to be found in the correct parent control context which Modal Popup cannot do. The solution is to use a dummy (hidden) control on the page/user control as a target control for the modal popup and then use extender's java-script API to hide/show popup as per needs (see this article for client side API).

Change the Access Modifiers of ASP.NET controls

If I put a control in a .aspx file like this;
<asp:TextBox ID="protectedTextBox" runat="server">Some info</asp:TextBox>
I get a declared control in the page's .aspx.designer.cs file;
protected global::System.Web.UI.WebControls.TextBox protectedTextBox;
But I'd like to change the access modifier of the control to public. Is there any attribute or similar that I can set to change the access modifier?
Here's why I want to do it. I am trying to have cross-page postbacks work nice and neatly. I have two pages:
FirstPage.aspx
MyTextBox : textbox
MyButton : button, #PostbackUrl=Secondpage
SecondPage.aspx
MyLabel : label
When the user clicks FirstPage.MyButton, I want to write the value of FirstPage.MyTextBox.Text into SecondPage.MyLabel.Text. I could do it with Page.FindControl, but this seems like a poor substitute to casting the previous page as a FirstPage object and referring directly to the MyTextBox control on it. Something like this;
// on the page_load of SecondPage.aspx;
var previousPage = this.PreviousPage as FirstPage;
this.MyLabel.Text = previousPage.MyTextBox.Text;
Is there any way to change the access modifier?
You can just delete the declaration from the designer and put it in your code behind.
The comments around the declaration say to do this.
/// To modify move field declaration from designer file to code-behind file.
One option I've considered is writing a public property which exposes the original page;
public TextBox PublicTextBox { get { return this.MyTextBox; } }
Which would get the job done, but seems hacky.
Steve, exposing that page's controls would make sense if you'd need to manipulate those controls, but in your case you just need to pass some data (that string) to the other handler, so I would expose that and not the control itself.

Can I change the text of a label in a masterpage when loading a content page?

I have a label in a master page (sample.master) called lblHeading.
I want to dynamically change the text of the label when I load the content page.
I need to do this because I want to change the heading to something meaningful but only after I know about the content of the page.
Is this possible?
yes, you can in this very simple way........
((Label)Master.FindControl("lblHeading")).Text = "your new text";
Yes.
You want to create a strongly-type master page and you can then access it's properties from your content page during Page_Load or wherever else.
Yes, it is possible. MasterPage behaves just like UserControl in your page.
Possible steps to implement this:
Create a property or method on the MasterPage that enables you to make changes to the Label. E.g.:
public void ChangeLabel(string label) {
lblHeading.Text = label;
}
From your Page, get the reference to the MasterPage by using the Page.Master property.
Call the method defined in step 1 to change the MasterPage contents.
Additional info: You may need to cast Page.Master into your MasterPage type, try Coding the Wheel's link for instructions on how to do that.
Do as stated above. Then, e.g., from your page do this (master page has label with ID="Label_welcome"):
Label mpLabel = (Label)Page.Master.FindControl("Label_welcome");
if (mpLabel != null)
{
mpLabel.Text = "Welcome Fazio!";
}
You can create a public property in the masterpage that will change the label.
public string Heading
{
set
{
lblHeading.text = value;
}
}
It also depends on how deep your controls inside the Master page are. In my case, I had a Label control inside a ContentPlaceHolder control... so I had to do this...
Label myLBL = this.Master.FindControl("HeaderContent").FindControl("myLabel") as Label;

Calling a parent page code behind method from a child page code behind - ASP.NET 2.0 Page Inheritance model

What would be the best way to call a method in the code-behind of parent page from the code behind of the child page in the ASP.NET 2.0 Web Site model?
Scenario: User clicks a link in the parent page to view a data record's detail in child page (The parent and child are tow seperate pages). The user will modified the data in the client page. Once the child page has processed the update, the child page will close and I need to rebind the parent page to reflect the update.
I did something similar, but it was calling the parent page from a user control that was included in the parent page
if(Page.GetType().ToString().Contains("ASP.Default_aspx"))
{
MethodInfo MyMethod = this.Parent.TemplateControl.GetType().GetMethod("MyMethod");
MyMethod.Invoke(this.Page, null);
MyMethod = null;
}
UPDATE: I have to do this from the code behind because the child page closes after the data has been updated.
Easiest way would be to do the whole thing on one page using a multiview or some such thing.
Other then that, with javascript you can call
document.opener.location.href = "url";
to change the url on the parent page. You could just keep it the same, or stick stuff in the query string and muck with those values on Page_Load
If you're opening the child page in a modal pop-up, you can access window.returnValue on the parent page (via JavaScript) and then invoke a page refresh or an Ajaxy rebind call.
Check this page out for how to return value from modal pop-up and do something based on that value on parent page.
However, if you have the option, I'd get away from opening the edit form in a separate page. I'd put the edit form in a user control and show/hide it a la lightbox style.
Not sure if this is exactly what you want but you could have used cross page posting for this. This allows you to post back to the parent page from the child page with the advantage of having access to the child page's ViewState. To do this you set the PostBackUrl property of a button to the child page. In the parent page you can then access the PreviousPage property to retrieve values from the child page. So in the child page have a button such as:
<asp:Button ID="Button1" runat="server" Text="Update data"
PostBackUrl="~/Parent.aspx" onclick="Button1_Click" />
Then in the Parent.aspx Page_Load event:
protected void Page_Load(object sender, EventArgs e) {
if (IsCrossPagePostBack) {
Page prevPage = this.PreviousPage;
string myVal = prevPage.FindControl("myTextBox1").ToString();
string myVal2 = prevPage.FindControl("myTextBox2").ToString();
//etc
}
}

Categories