User control that replaces some another control on aspx page - asp.net

I have a control on a page (let's say a button). I want to create such a user control, that will have a property TargetControlID, which takes an ID of control (button) on a page and on render will replace (hide) it with another button (a clone of a first button). Is it possible? Did anyone ever made such thing?

It's certainly possible, but I would suggest an alternate approach that will have fewer problems.
Instead of replacing the target control, just hide it by setting it's visibility to false. This way any processing that it does will still work, control ID's will remain static on rendering (automatically generated control ID's depend on order of controls), and it will have the same effect as you're looking for.

Yes, you can do what you're talking about. Create your user control in the usual way. Here's a link in case you're not familiar with that: Creating a User Control
Then create a property in the code-behind like this:
public string TargetControlID { get; set; }
Once it is a property, you can access it through the html:
<Azat:AzatButton ID="abtn1" runat="server" TargetControlID="btnOtherButton1" />
Then in the Page_Load() event handler, you instantiate a button based on this.abtn1.TargetControlID and remove abtn1 from the Page's Controls collection.
this.Controls.Remove(this.abtn1);

Related

Hide Checkbox on a particular page

I am working on ASP.NET application where I am reusing a user control. The user control contains a checkbox and bunch of other controls. I want to display all the controls inside the user control on all the pages but on one single page I want to hide the checkbox.
I was thinking that I can use the databind methods and see if I am on the "pagex" then hide the checkbox. Is there any other way to solve this problem?
If you have access to the code for the control you should be add a new property to the control for hiding/showing the checkbox and then just pass in the property depending upon what page you are on. You'd have to pass in the show/hide property on the load event of the page.
Do you have access to the code??
I would specify a parameter in the code behind for your ascx file. Example:
public bool HideCB = false;
THen when you put your User Control on your aspx page do this:
<uc:TestControl id="TestControl" runat="Server" HideCB="true" />
This way you can do a check on if(HideCB) to determine if you want to make it visible or not.

Changing Appearance of Master Page based on Content Page

My Master Page has a heading with tabs. The code looks something like:
<CT:Tab ID="tabHome" runat="server" Url="/index.aspx" Text = "Home" Highlight="true" />
<CT:Tab ID="tabFun" runat="server" Url="/fun.html" Text = "Fun"/>
<CT:Tab ID="tabBlog" runat="server" Url="/blog" Text = "Blog"/>
I can think of two ways to control which tab is highlighted from within a user control:
Have the user control implement an interface. The master page can decide which tab to highlight based on which interface is implemented, or based on a method in the interface that returns a string.
In the Page_Load (or Page_Init) function, tell the master page (via FindControl or via a function in the Master Page) which control to highlight.
I don't really like either of these solutions. Is there a clean way I could control which tab is highlighted from the control at design time (i.e., in the aspx file)?
The best way I can think of is:
Create an event delegate on the UserControl that passes a parameter indicating which user control to highlight
Handle this on the master page; so whenever the event is fired it chooses the correct tab to highlight based on the parameter passed
Fire the event on the user control Page_Init
A good start on events and delegates is at MSDN here:
http://msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx

Changing Dynamic Controls via DropDownList on Content Page

Problem: Content Page with Wizard Control with UpdatePanel and Placeholder. Above the UpdatePanel is a DropDownList. I need to display different input controls below the drop-down list when the user changes the selection in the drop-down list. When the user clicks 'Next' on the wizard control, I need to be able to get the data out of those dynamic controls as well.
I know all the dynamic controls have to be created in the OnInit method in order to get the data back from those controls during the postback. However, when the drop-down list's SelectedIndexChanged event is fired, the OnInit method is called... then the PageLoad... and finally the handler for the SelectedIndexChanged event is called. ViewState hasn't been restored until well after the OnInit & PageLoad methods have been called, so there is no way to know what the user chose in the list box at the time OnInit is called... which exactly when I'm required to create the dynamic controls.
So... how do you solve this problem? Do you just have to write the entire page, or most of it, using JavaScript?
Thanks in advance.
I tend to use an old school method for this type of requirement. I would write all of the controls that are needed in the update panel, with their Visible property set to false. Then, on post back read the drop down's state and set the approperate controls Visible property to true. This way there is no "dynamic" controls, and due to the fact that controls whose Visible property is false are not rendered, they are not downloaded until the user should see them.
you can also use an asp:hiddenfield and set the value to a case var you mentally create. then run a small jQuery script on top to look at
$(document).on("change", "#ddlSelector", setControls);
then just make a function, for instance:
function setControls(event) {
event.preventDefault();
var selector = hiddenfield.val();
}
then any item to show/hide can be done with getting the tag:
$("#elementName").css("display", "inline");
or display, none to hide.
I used this at work because at times you need to change without firing the postback, but still collect data when they engage the form.
I typically avoid jQuery for many events for strength of code and security, but DOM element manipulation can be much easier at times with jQuery.

using same ascx control twice while using Register (ASP.NET)

I'm using Register at the top of the page to register an ascx control, now the thing is I want to use this control twice on the page.
Now, the problem is when I hit buttons of one instance of the control, it fires the validation of both of the controls, and it obviously breaks, because it should be validating only one control - itself! The reason I am sure about this is because if I keep only one instance of the control on the page, then it flows nicely.
What I already tried that did NOT work:
1)Putting the two instances in different ASP Panels.
2)Registering the control twice at top of the page, so each registration has only one instance on the page.
I would not like to modify the validation of the control itself, but it's a huge project and it is being used at other places, and I do not want to disrupt other things. FYI It's using "Page.IsValid" to validate.
Set the ValidationGroup property of the validators and the ValidationGroup property of the buttons dynamically in the Page_Load method of the user control. You can use the user control's ID property as part of the ValidationGroup to differentiate between the two controls.
e.g.,
myRequiredValidator.ValidationGroup = "valGroup_" + this.ID;
myButton.ValidationGroup = "valGroup_" + this.ID;

Dynamically Change User Control in ASP.Net

I'm trying to create a web page that will display an appropriate user control based on the selected value of a drop down list.
Basically the page layout is this:
Drop Down Selection
< User Control created based on drop down selection >
I have it half working... the controls are changing when the selection changes.
In OnInit(), I dynamically create the last selected control (whose value gets saved in session state because ViewState isn't available at OnInit).
When the drop down selection change occurs, I remove the old user control, and add a new one. The problem is: with the new control being added from the selection changed event, I'm not able to save changes from the user on the first postback. After the first post back, the selected control is created from OnInit instead of the Change event, and state is saved from then on, until the next selection change.
Here is the SelectionChanged method:
protected void SelectionChanged(object sender, EventArgs e)
{
SelectedValue = int.Parse(DropDownList.SelectedValue); //Store in Session
Control userControl = GetSpecificUserControl(SelectedValue);
PlaceHolder1.Controls.Clear(); // Remove old user control
PlaceHolder1.Controls.Add(userControl);
}
Any changes made to the new control by the user after SelectionChanged happens are not saved on the following post back. However, subsequent postbacks do get saved. At that point, the control is getting created in OnInit().
Is there some way to force the correct post back and ViewState when the control changes? Is it possible to force a page reinitialization after the control is changed?
What you need to do is keep the last known value of the DropDownList in the Session. Then:
OnInit:
Create whatever control is indicated by the saved value in the session
SelectionChanged Event
Remove whatever you created during OnInit
Create and add new control based on new DropDownList selection
Save new DropDownList selection in session
This way, on the next postback after a change you are re-creating the control that ViewState expected to find, and so it's state will be restored.
Dynamic controls can be very finicky. Often it is easier to create all of the controls you might possible need and set their Visible properties to false. This way they don't render to the browser at all. Then set Visible to true for just the controls you need when you need them.
This is the classic tear-your-hair-out problem with ASP.Net webforms. You have several options:
1) This is a bit of a hack, since it goes outside the intended page lifecycle a bit, but in my experience it's the most direct way of dealing with the problem. When the page posts back from the drop down selection event, simply poll Request["MyDropDownID"] for the selected value of the drop down control during Init() - don't wait for the OnMyDropDownChanged() event to set up your page.
2) Implement your own ViewState handling for your user controls. This requires digging into the ViewState documentation and overriding a number of methods.
3) Joel's solution. He beat me to it but I was trying to get first post :p
Other options involve posting values using javascript and such, but those get really messy.
If the list of options is not too big, you could just render all the user controls statically and use JavaScript/jQuery to show/hide the appropriate controls based on the value of the dropdown (onchange js event). You can use the dropdown value to extract the appropriate values from the user controls when saving.
You avoid the pain of dealing with dynamic controls, provide a more responsive UI when selecting from the dropdown (no postback), etc...
Don't add the control in the SelectedIndexChanged handler, add it during Page_Load. You'll just have to test the value of the dropdown each time the page loads, and load the correct control for that value.

Resources