User control not added to panel via code? - c#

I have a panel inside an update panel on my page which is pre-loaded with a user control, and I want to remove this control and add a new one instead (after a user does some action)
I registered the control:
<%# Register src="~/UserControls/FilesControl.ascx" tagname="FilesControl" tagprefix="files" %>
<asp:Panel ID="pnlFiles" CssClass="selected_tab" runat="server" ClientIDMode="Static">
<files:FilesControl runat="server" ID="filesControl" ShowSearchParams="false" ShowExportControl="false" />
</asp:Panel>
And for adding the new control I wrote this code:
pnlFiles.Controls.Clear();
FilesControl filesHistory = (FilesControl)LoadControl("~/UserControls/FilesControl.ascx");
filesHistory.ShowExportControl =
filesHistory.ShowSearchParams = false;
InitHistoryControl<FilesControl>(filesHistory, daysBack, true); //Sets a datasource to a grid view in the control
pnlFiles.Controls.Add(filesHistory);
But the control is not added to the panel, I don't get any errors even in debug, it is just not there. I can't even see it in the html on view source.

Perhaps because you have these lines:
filesHistory.ShowExportControl =
filesHistory.ShowSearchParams = false;
Try something like:
filesHistory.ShowExportControl = true;
filesHistory.ShowSearchParams = false;

Related

c# asp.net master page get a href and set visible to false

I have an a href link in my user.master page, but I'm unable to find that control in my user.master.cs. How do I do so? I tried using master and find control, but it says object reference is not instance to an object or it does not work. Please help, thanks.
user.master
Upgrade
user.master.cs
(first try)
var masterPage = Master;
if (masterPage != null)
{
masterPage.FindControl("showUpgradeLink").Visible = true;
}
(second try)
this.Master.FindControl("showUpgradeLink").Visible = false;
Did you put runat="server" on the a tag?
For example:
<a href="ViewPremiumPlans.aspx" id="showUpgradeLink" runat="server" class="btn-light btn-sm" >Upgrade</a>
You need to add runat="server" without that it is not a server control.
Upgrade
You then access it in the master (user.master.cs) page directly
showUpgradeLink.visible = false;
If you want to expose it to child pages add a public property to user.master.cs
public HtmlGenericControl UpgradeLink { get { return showUpgradeLink; } };
In your child aspx pages where you want to access the control/property add:
<%# MasterType virtualpath="~/Path/To/user.master" %>
Then in the child .cs pages you can use:
Page.Master.UpgradeLink.visible = false;

ASP.Net WebForms LinkButton click, open new tab, passing id through hidden html input variable

I have an aspx webforms page with a repeater built through a user control. Each repeater item has a link button. What I want to happen is that when the LinkButton (in the repeater on page A's user control) is clicked, the url is opened in a new tab, and a hidden id next to that LinkButton is passed (according web development best practices for security if possible) to the aspx page (page B) in the new tab. Both pages A and page B are in the same application.The intent of what I described above is so that the user can easily return to their search results after returning from the URL opened by clicking on the LinkButton.I am open to ideas on how to do this that are closer to standard best-practice methods.
So far, I have tried:
1) cross-page posting – this worked for passing the id, but not for opening in a new tab.
2) Setting the PostBackUrl to page B's url, setting the Page.Form.Target="_blank" with OnClientClick calling javascript to set the hidden id from the user control to the value of an html hidden input on page B and also.
3) I also tried using window.open("page B url", "_newtab") in OnClientClick.
a) So far, the only method that worked correctly was the 2nd one from the 3 different methods above. However, after page B is loaded in the new tab, I don't know how to reset page A's Page.Form.Target back to what it was previously before setting it to "_blank"
b) The methods that I have tried, to no avail, to reset the Page.Form.Target have been:
1) Resetting the target in page A's Page_Load where IsPostBack == true --> that caused Page B to load with the same content as Page A.
2) Resetting the target in page A's user control's Page_Load --> same result as method 1
3) Resetting the target in page A’s user control’s LinkButton’s OnUnLoad in page A's user control --> same result as method 1
4) Resetting the target in javascript through the LinkButton’s OnClientClick --> didn’t work
5) Resetting the target in page B's Page_Load using a public variable from page A containing a reference to page A's form (similar to what can be done through cross-page posting) --> didn’t work.
What I am thinking about trying next is:
1) Wrapping another user control on page A to display page B's content, in an asp Panel (Panel B)
2) Put page B’s content into the new user control page
3) Wrapping the search results content on page A in an asp Panel (Panel A).
4) When the LinkButton in the repeater on the new user control is clicked, the search results content in Panel A will be hidden, and Panel B will be shown.
5) When the user wants to return to the search results, they will click on a ‘Return to Search’ LinkButton in Panel B’s content, and then Panel B will be hidden, then content of Panel B will be cleared, and Panel A will be shown again.
I'm not yet sure if that will work though. It doesn't seem like this should be that difficult. It is a straight-forward concept, and I would think is a fairly common situation in web development.
I feel like Wiley Coyote trying to catch the Road Runner because I come up with elaborate intelligent, thought-out plans that all completely fail. I am now holding up a little sign that says, "Help!
I had the same issue resolve by the following code you just try this in ur HTML page for a button in GRIDVIEW:
<asp:LinkButton ID="LinkButton1" runat="server" Text="View" CommandArgument='<%# Bind("ref") %>'
OnClick="LinkButton1_Click" OnClientClick="document.forms[0].target ='_blank';">View</asp:LinkButton>***
I actually got this figured out.
I figured it out through a combination of the marked-answer on this post, How to Open new tab when we click on LinkButton, and the marked-answer on this post, Is it possible add click event to hyperlink?.
My Repeater ItemTemplate in the user control's repeater looks similar to this:
<asp:HiddenField ID="hfId" runat="server"
Value='<%# Eval("Id") %>'/>
<asp:HyperLink ID="myLink" runat="server"
Text='<%# Eval("Name") %>'
NavigateUrl="/myUrl.aspx"
Target="_blank" />
<asp:Button ID="btnSubmit" runat="server"
Text="Submit"
OnClick="BtnClick"
Style="display: none;" />
This is my code in the ItemDataBound of the repeater:
protected void RptrItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var myId = "";
var myNameLink = e.Item.FindControl("myLink") as HyperLink;
if (myNameLink != null)
{
var submitButton = e.Item.FindControl("btnSubmit") as Button;
if (submitButton != null)
{
var submitButtonClientId = submitButton.ClientID;
myNameLink.Attributes.Add("onclick", "onNameClick('" + submitButtonClientId + "')");
}
}
}
}//end RptrItemDataBound
The javascript code:
<script type="text/javascript">
function nameClick(buttonId)
{
document.getElementById(buttonId).click();
}
</script>
And here is the BtnClick C# code:
protected void BtnClick(object sender, EventArgs e)
{
var btnSelect = sender as Button;
if (btnSelect == null)
{
return;
}
var myListItem = (RepeaterItem)btnSelect.DataItemContainer;
if (myListItem != null)
{
var hfId = myListItem.FindControl("hfId") as HiddenField;
if (hfId != null)
{
var intId = int.Parse(hfId.Value);
Session["selectedId"] = intId;
}//end if (hfId != null)
}//end if (myListItem != null)
}//end btnClick

Populate ITemplate by code

Is there a way to fill an ITemplate by code?
Let's suppose I have an UpdatePanel:
UpdatePanel upnl = new UpdatePanel();
// What should be done next?
//upnl.ContentTemplate = ...
and the result of it would be equivalent of:
<asp:UpdatePanel runat="server" ID="upnl">
<ContentTemplate>
test
</ContentTemplate>
</asp:UpdatePanel>
This will do if I understood your question correctly:
public class YourTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
container.Controls.Add(new LiteralControl("test"));
}
}
...
upnl.ContentTemplate = new YourTemplate();
All the Template enabled Controls in ASP.net must implement System.Web.UI.ITemplate interface to create Template at run time.
But You need not to create custom Template class in case of update
panel. Check UpdatePanel.ContentTemplateContainer Property -
The ContentTemplateContainer property enables you to programmatically add child controls to the UpdatePanel control without having to define a custom template that inherits from the ITemplate interface. If you are adding content to the UpdatePanel control declaratively or through a designer, you should add content to the ContentTemplate property by using a <ContentTemplate> element.
Check this code snippet- For more details check the ContentTemplateContainer link above.
UpdatePanel up1 = new UpdatePanel();
up1.ID = "UpdatePanel1";
Button button1 = new Button();
button1.ID = "Button1";
button1.Text = "Submit";
button1.Click += new EventHandler(Button_Click);
up1.ContentTemplateContainer.Controls.Add(button1);
Page.Form.Controls.Add(up1);

ASP.NET OnClick not firing in Repeater.ItemTemplate that has a custom control

Title is a bit of a mouthful, but I'm a bit stuck on this issue.
I have a search result page with has a custom control that has a Repeater. The ItemTemplate in the repeater is a PlaceHolder so I can construct the Item in a particular format; more specifically, I have a string of 'diseases' that come in the form of Disease1|disease2|disease3 and need to be given links for each disease.
Now for some code:
The following is the SearchResultControl.ascx
<asp:Panel ID="SearchResultPanel" runat="server" ScrollBars="Auto">
<asp:Repeater ID="Repeater1" runat="server"
onitemcreated="Repeater1_ItemCreated"
onitemcommand="Repeater1_ItemCommand">
<ItemTemplate>
<asp:PlaceHolder ID="ItemTemplatePlaceHolder" runat="server">
</asp:PlaceHolder>
</ItemTemplate>
<SeparatorTemplate>
<tr>
<td colspan="6"><hr /></td>
</tr>
</SeparatorTemplate>
</asp:Repeater>
</asp:Panel>
The code behind: SearchResultControl.ascx.cs
protected void Repeater1_ItemCreated(object sender, RepeaterItemEventArgs e)
{
if (e.Item.DataItem != null)
{
PlaceHolder placeHolder = e.Item.FindControl("ItemTemplatePlaceHolder") as PlaceHolder;
Control searchResultItem = Page.LoadControl("SearchResultItem.ascx");
DataRow row = (e.Item.DataItem as DataRowView).Row;
if (row != null)
{
string diseaseState = row["DiseaseStates"] as string;
searchResultItem.GetType().GetProperty("DiseaseStates").SetValue(searchResultItem, diseaseState, null);
placeHolder.Controls.Add(searchResultItem);
}
}
}
(Full disclosure, I got this idea from this question)
The SetValue calls the DiseaseStates property in SearchResultItem which in turn calls the following method to build the links, set the text, and the events:
private void BuildDiseaseStateLabels(string diseaseStates)
{
PlaceHolder placeHolder = FindControl("DiseaseStatePlaceHolder") as PlaceHolder;
string[] diseaseStateSplit = diseaseStates.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
int count = diseaseStateSplit.Length;
foreach (string diseaseState in diseaseStateSplit)
{
LinkButton diseaseStateLink = new LinkButton();
diseaseStateLink.Text = diseaseState;
//diseaseStateLink.Click += new EventHandler(OnDiseaseStateLinkClick);
diseaseStateLink.CommandArgument = "<%# Eval(\"PatientID\")+ \";\" + Eval(\"PatientStatus\")+ \";\" + Eval(\"Age\")+ \";\" + Eval(\"DiseaseStates\")%>";
diseaseStateLink.CommandName = "OnDiseaseStateLinkClick";
//diseaseStateLink.Command += new CommandEventHandler(OnDiseaseStateLinkClick);
placeHolder.Controls.Add(diseaseStateLink);
if (count != 0)
{
Label splitLabel = new Label();
splitLabel.Text = "|";
placeHolder.Controls.Add(splitLabel);
}
}
}
This is the layout for the SearchResultItem
<div id="SearchResultItemDiv" class="MainSearchResultItem">
<asp:PlaceHolder ID="DiseaseStatePlaceHolder" runat="server">
</asp:PlaceHolder>
</div>
Initially I tried setting the Click event, but that doesn't work at all. I then set the CommandArgument and CommandName but that didn't seem to do the trick. I figured the Command event might need to be set, but again, no luck. I should note that when a link is clicked the Repeater1_ItemCreated in SearchResultControl.ascx.cs is called. But since there is no data in e.Item.DataItem is null and I lose the results.
In one of the questions regarding the same issue, it was suggested that the OnItemCommand be added, but even that doesn't get called.
I also read A Stumper of an ASP.NET Question and A Stumper of an ASP.NET Question: SOLVED!, to no avail.
What could I possibly be doing wrong? All of the correct event hookups seem there, I'm checking for IsPostBack and not doing DataBind() again. blaaargharaggh
Help is always greatly appreciate.
I believe you're running into this issue because the LinkButton controls are recreated too late in the page lifecycle. You have to remember that when the page is posted back, the control technically does not exist anymore, so the event handler cannot be fired.
If you can recreate the LinkButton controls somewhere before the Page_Load event is reached, like OnInit for example, everything should work fine.
For simple pages the above usually works very well, but there are circumstances where recreating controls during OnInit requires a lot of overhead, such as storing counters or arrays in ViewState so you can keep track of the controls that need to be recreated after postback. In these situations I would suggest taking a look at the DynamicControlsPlaceHolder by Denis Bauer. This control is capable of persisting dynamic controls without any addtional code required, which is pretty awesome.
Here's a link to the latest version:
http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx
The problem might be that you're not doing the DataBind() again.
Because you're building the buttons on the fly, when the page post backs, the buttons haven't been created and are unable to work out which click event it should be firing.
Try getting rid of the IsPostBack check, so each time the page loads, you're re-build the repeater.

Fetch JS return value in server side page_load event in asp.net

I have an aspx master/content page scenario. The parent page has an IFrame which points to a child.aspx. The child.aspx has a checkbox, On page_load of child.aspx, I want to show/hide the checkbox depending on the following logic:
- if the child.aspx is opened directly, then I have to show the checkbox.
- if the child.aspx is opened in the IFrame, then I have to hide the checkbox.
Basically, I want to check in child.aspx, if it contains a parent window then hide the checkbox control otherwise show it.
I will prefer the show/hide code in codebehind in Page_load event as I have to execute some more logic depending on whether the it is opened from parent window or not.
Till now I did the following:
In child.aspx
<asp:Content ID="Content1" ContentPlaceHolderID="Main" Runat="Server">
<script language="javascript" type="text/javascript">
function DoesParentExists()
{
var bool = (parent.location == window.location)? false : true;
var HClientID ='<%=hfDoesParentExist.ClientID%>';
document.getElementById(HClientID).Value = bool;
}
</script>
<div>
<h2>Content - In IFrame</h2>
<asp:HiddenField runat="server" id="hfDoesParentExist" />
<asp:CheckBox ID="chkValid" runat="server" />
<asp:ImageButton ID="ImageButton_FillW8Online" ImageUrl="~/images/expand.gif"
OnClick="btnVerify_Click" runat="server" style="height: 11px" />
</div>
</asp:Content>
in client.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "DoesParentExists", "DoesParentExists()", true);
if (hfDoesParentExist.Value == "true")
{
chkValid.Visible = false;
}
}
Using RegisterClientScriptBlock, I get error in JS. That the object hfDoesParentExist doesn't exist 'coz the control is not yet created. Right? I tried using RegisterStartupScript but in codebehind I always get null in hidden variable. I don't want to use the on button click or something like it. I need it on page_load event only. How to resolve the issue?
This line:
document.getElementById(HClientID).Value = bool;
Should be: (lower case value)
document.getElementById(HClientID).value = bool;
Also you cannot check the value of a hidden field set by javascript register callback, in the current executing context on the server side.
I would move the logic to the client side to hide or show the checkbox. If the field must indeed be removed from the page you can do that as well with javascript.
function DoesParentExists()
{
var bool = (parent.location == window.location)? false : true;
var cehckboxId ='<%=chkValid.ClientID%>';
if(bool){
document.getElementById(cehckboxId).style.display = 'none';
}
else {
document.getElementById(cehckboxId).style.display = 'block';
}
}
You may want to wrap the checkbox with a div and hide the container also to include the label.
To do it server-side, I would rely on a querystring parameter. Have the parent page load the child page by appending ?inframe=1. Then check for that value in your Page_Load.

Categories