How to put one user control into another user control - asp.net

suppose i have two user control. usercontrolA and usercontrolB. how to include usercontrolB into usercontrolA. also please tell me how to read controls value of usercontrolB from usercontrolA and also from page. looking for details discussion. thanks

May be below can help you
In Control A
<%# Register Src="~/UserControls/ControlB.ascx" TagName="ControlB" TagPrefix="uc" %>
<uc:ControlB ID="myControlB" runat="server" />
In Control A.ascx.cs
string userName=myControlB.UserNameTextBox.Text;
In User ControlB.ascx.cs have some properties like
public TextBox UserNameTextBox
{
get {return this.txtUserName;}
}

Related

ASP.NET ASCX Use of Instance Variable

Let's say I have an ASCX user control that requires access to the current user's full name. An ASPX page contains this line at the top
<%# Register src="top.ascx" tagprefix="custom" tagname="top" %>
and this line in the body:
<custom:top runat="server" />
The ASPX file knows the user ID of the current user and could determine his full name. So how can I use the code run by the ASPX file to provide its information to the ASCX file?
Declare a property on the UserControl and have the parent page set it.
On your usercontrol:
public string FullName { get; set; }
On the aspx page either set it in the code behind
YourUserControl.FullName = FullName
or through markup
<custom:top runat="server" FullName="<%= SomeProperty %>" />
You could use the Page property of the user control and cast it to the instance of your page. Then, call the method of your page class to get the user name.
To make this work in a dynamically compiled project, you have to do a little more work to have the control recognize the data type of the dynamically compiled page. Here is a short tutorial on how to do.
Or, as Brandon outlines, do the opposite and let your page tell your user control the information.
This sounds like you might be mistaken about how the page lifecycle works and how you can expose data across your controls. For example, lets say you have this code in your ASPX:
public override void OnLoad(EventArgs e)
{
string userName = "Bob";
}
In your ASPX file, you can reference the control and set a property on it to pass the data along:
<custom:top ID="someControl" runat="server" />
You expose a property in your top control like so:
public string UserName { get; set; }
You could then add this code to your OnLoad method:
someControl.UserName = userName;
Then your control will have access to that data. Alternatively, you can stick things in the Request cache if you dont have a direct line to the control:
HttpContext.Current.Items["key"] = userName;
And then pull the data from your control via the same fashion:
string fromCache = HttpContext.Current.Items["key"];
You could go about this in several ways. I typically use a session variable, since the user will be bound to the session.
In the ASPX (or when the user logs in):
Session["UserFullName"] = GetFullName(); //Code to get full name here
In the ASMX:
this.FullName = Session["UserFullName"]; //TODO: Check for null values

InstantiateIn and user controls

I want to add my user control in InstantiateIn like this:
public void InstantiateIn(Control container)
{
PIMVisualizer pimVisualizer = new PIMVisualizer();
container.Controls.Add(pimVisualizer);
container.Controls.Add(new Button() {Text="asdf"});
}
but the control doeas not appear on the page (the button does). The control is trivial, I am just testing the approach:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="PIMVisualizer.ascx.cs" Inherits="PIMVisualizer" %><asp:Label ID="Label1" runat="server" Text="UC"></asp:Label>
but still, why does not the text "UC" appear onthe page?
You have to load UserControls, do not create them via constructor.

Remove unwanted id for a control when declared in asp:content in ASP.NET

Consider sample piece of code in asp.net which has a master page associated with it
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolderA" Runat="Server" >
<asp:TextBox ID="TextBoxB" runat="server" CausesValidation="True" Height="96px" Width="426px" />
</asp:Content>
When the page is rendered in browser id generated for textbox with id "TextBoxB" is
ctl00_ContentPlaceHolderA_TextBoxB
Below is the equivalent html code.
<input name="ctl00$ContentPlaceHolderA$TextBoxB" type="text" id="ctl00_ContentPlaceHolderA_TextBoxB" style="height:96px;width:426px;" />
Is it possible to have same id of TextBoxB in both HTML and aspx page.
Thanks in Advance.
No. The ID has to be unique on the HTML page, but there's no way for the ASPX page to be certain that the ID you've given is unique - it could be duplicated in for example the master page, in a user control, etc, and then you end up with two identical IDs in the output.
To get around this, ASP.NET guarantees unique IDs by qualifying an ID with the IDs of containing controls.
If you were using .NET 4.0 (I guess #Nick means the same) you could set ClientIDMode="Static" so control would have the same ID as it has in markup.
If you not using .net 4.0, but you wont to have the same id (on the html page and server side)
try this:
public class MyTextBox : TextBox
{
public override string UniqueID
{
get
{
return this.ID;
}
}
}
MyTextBox textBox= new MyTextBox();
textBox.ID = "id";
textBox.Text = "text";
this.Page.Controls.add(textBox);

Access child user control's property in parent user control

I have included a user control in another statically following code :
place the folowing directive in the asp code of the parent page or
usercontrol:
<%# Register src="Name_of_your_child_control.ascx"
tagname="Name_of_your_child_control" tagprefix="uc1" %>
use the following tag in the asp-code of the parent page/control:
<uc1:Name_of_your_child_control ID="Name_of_your_child_control1"
runat="server" />
.....
But the issue is...i am not able to access the public properties of user control which got included(child user control) in given user control(parent user control)...
Please help :(
Say your usercontrol was this:
<%# Control Inherits="Project.MyControl" Codebehind="MyControl.ascx.cs" %>
<asp:TextBox ID="TB" runat="server" />
Your control code-behind:
namespace Project
{
public partial class MyControl : UserControl
{
public string MyTextProperty
{
get { return TB.Text; }
set { TB.Text = value; }
}
}
}
In your parent page that included the control, like this:
<%# Register src="~/MyControl.ascx" tagname="MyControl" tagprefix="uc1" %>
<uc1:MyControl ID="MyControlID" runat="server" />
You can use that property in code:
MyControlID.MyTextProperty = "bob";
Using
Name_of_your_child_control1.PublicPropertyName
must work for your parent user control.
Check the path and file names you are using, Anish. You have something wrong. Is Visual Studio telling you it can't find the control? Is it failing at compile time? Runtime?
It's funny but whenever you add a property to a user control.
You need to register it again in the parent. So in your case,
Add a space at the end of this line and remove it again:
$<% Register src="~/MyControl.ascx" tagname="MyControl" tagprefix="uc1" %>
This will re - register the user control and you will be able to access new properties.

Completely remove ViewState for specific pages

I have a site that features some pages which do not require any post-back functionality. They simply display static HTML and don't even have any associated code. However, since the Master Page has a <form runat="server"> tag which wraps all ContentPlaceHolders, the resulting HTML always contains the ViewState field, i.e:
<input
type="hidden"
id="__VIEWSTATE"
value="/wEPDwUKMjEwNDQyMTMxM2Rk0XhpfvawD3g+fsmZqmeRoPnb9kI="
/>
EDIT: I tried both variants of setting EnableViewState on page level with no luck at all:
<%# Page Language="C#" EnableViewState="false" %>
<%# Page Language="C#" EnableViewState="true" %>
I realize, that when decrypted, this value of the input field corresponds to the <form> tag which I cannot remove because it is on my master page. However, I would still like to remove the ViewState field for pages that only display static HTML. Is it possible?
You could override Render and strip it out with a Regex.
Sample as requested. (NB: Overhead of doing this would almost certainly be greater than any possible benefit though!)
[edit: this function was also useful for stripping all hidden input boxes for using the HTML output as a word doc by changing the MIMEType and file extension]
protected override void Render(HtmlTextWriter output)
{
StringWriter stringWriter = new StringWriter();
HtmlTextWriter textWriter = new HtmlTextWriter(stringWriter);
base.Render(textWriter);
textWriter.Close();
string strOutput = stringWriter.GetStringBuilder().ToString();
strOutput = Regex.Replace(strOutput, "<input[^>]*id=\"__VIEWSTATE\"[^>]*>", "", RegexOptions.Singleline);
output.Write(strOutput);
}
Add following methods to the page:
protected override void SavePageStateToPersistenceMedium(object state)
{
//base.SavePageStateToPersistenceMedium(state);
}
protected override object LoadPageStateFromPersistenceMedium()
{
return null; //return base.LoadPageStateFromPersistenceMedium();
}
protected override object SaveViewState()
{
return null;// base.SaveViewState();
}
Result :
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="" />
In the <% #page... directive at the top of the page, add EnableViewState="False". That will prevent the ViewState for that particular page.
The method suggested by Martin must be used very carefully; because it may cause unexpected behaviors in your pages as Martin pointed in parenthesis. I've actually experienced it. But there is another option to remove viewstate content from page safely.
This option gives you the ability to use viewstate without setting false, it also allows you to remove it from your pages. Please check the articles below:
1- http://www.eggheadcafe.com/articles/20040613.asp
2- http://aspalliance.com/72
There is a solution file zipped under the Peter's article [1] you can download. I recommend that you read the second article also referenced by Peter. This is a perfect solution to remove viewstate content from your page while using its capabilities.
There will always be a ViewState. See this related question:
Why does __VIEWSTATE hidden field gets rendered even when I have the EnableViewState set to false
in .net4 you can just remove the runat="server" from the form tag. But you can't use server controls inside the form tag once you remove it.
ViewState is added only if an asp:Form is present in the page. Remove the Form, and the hidden field will not be rendered.
Beware: By doing this, you are also renouncing to have server-side event handlers, or any kind of PostBack events.
Or just use a simple jQuery line to remove the fields, if you're using AJAX-style postback requests...
$(".aspNetHidden").remove();
This removes the DIV encasing the hidden __VIEWSTATE fields.

Resources