the code written below displays the text box for a certain condition.But when i click another unrelated button or link it dissapears.i need it to stay visible when i do other activities on the webpage
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox new_textbox = new TextBox();
if (DropDownList1.Text.Equals("OFF"))
{
new_textbox.ID = "txt" + 1;
PlaceHolder1.Controls.Add(new_textbox);
Label5.Visible = true;
new_textbox.Visible = true;
}
else
{
Label5.Visible = false;
}
}
This question has been asked on SO before:
Dynamically added controls in Asp.Net
You are only adding this control in a certain situation, specifically when DropDownList1.Text.Equals("OFF"). Could you instead have a static control that you just set visible in this case?
According to msdn's Add Controls to an ASP.NET Web Page Programmatically:
Controls are typically added to the page during the page's
initialization stage. For details about page stages, see ASP.NET Page
Life Cycle Overview.
The quote links to ASP.NET Page Life Cycle Overview.
You have to be careful about adding controls dynamically, see this msdn page about Dynamic Web Server Controls and View State.
Related
I have 3 BladeItems in another page. And I want to navigate from MainPage to that page and bring the requested BladeItem into view. But it is not working.
I first thought it was because that the page has not been loaded. So I put it into the Page_Loaded. However, it is still now working. Why is that?
private void Page_Loaded(object sender, RoutedEventArgs e)
{
TitleBarHelper.SetDarkTitleBar();
Window.Current.SetTitleBar(AppTitleBar);
UpdateTitleBarLayout(Windows.ApplicationModel.Core.CoreApplication.GetCurrentView().TitleBar);
FullMediaControl.Update();
SetMusic(MediaHelper.CurrentMusic);
FullPlaylistControl.ScrollToMusic(MediaHelper.CurrentMusic);
if (MusicInfoRequestedWhenUnloaded)
{
MusicPropertyBladeItem.StartBringIntoView();
MusicInfoRequestedWhenUnloaded = false;
}
else if (LyricsRequestedWhenUnloaded)
{
LyricsBladeItem.StartBringIntoView();
LyricsRequestedWhenUnloaded = false;
}
}
Source Page Code is here. This page can be navigated using the "Show Lyrics" or "Music Info" item in the MenuFlyout at the right bottom more button.
And actually the FullPlaylistControl.ScrollToMusic in the code above is also not working. It just scrolls to a row in a ListView. I guess they might be the same reason.
This is the documentation for StartBringIntoView.
According to the instructions in the documentation, this method is only possible when the control is rendered on the visual tree, so you need to modify it when you call the method.
You want MusicPropertyBladeItem.StartBringIntoView() to work, you need to call it in the MusicPropertyBladeItem_Loaded event. For the same reason, you need to call ScrollToMusic when the FullPlaylistControl is loaded.
Page_Loaded only means that the page is loaded, but it doesn't mean that the controls have been rendered.
Best ragards.
I'm developing a custom server control in Asp.NET (.NET 3.5) which inherits the CompositeControl class. Inside my control I'm overriding the CreateChildControls() method to generate a mixture of html and Asp.NET server controls. Some of the Asp.NET controls which are added are LinkButtons (which each have their Command event handler set to a method within my control). What I'm finding is that the first time one of these LinkButtons is clicked a postback is triggered and the event handler method is correctly fired. Inside this event handler method CreateChildControls() is explicitly called to regenerate the control in response to the postback. What I then find is that subsequent clicks of the LinkButtons postbacks fail to raise the event handler method.
I assume that the way I'm handling the regeneration of the control on postback must be at fault, but I can't figure out what to do - I am aware of the fact that on that first postback CreateChildControls() is called twice which probably isn't ideal but since CreateChildControls is called before any events are raised, I don't see a way around this.
A simplified version of my control class is shown below:
public class SearchResults : CompositeControl
{
private int PageIndex = 0;
protected override void CreateChildControls()
{
//do stuff here e.g.
LinkButton prevLink = new LinkButton();
prevLink.Text = "< Prev";
prevLink.CommandArgument = (PageIndex - 1).ToString();
prevLink.Command += new CommandEventHandler(PagerLinkCommand);
this.Controls.Add(prevLink);
}
protected void PagerLinkCommand(object sender, CommandEventArgs e)
{
PageIndex = int.Parse(e.CommandArgument.ToString());
CreateChildControls();
}
}
EDIT
The problem here was caused by the fact that the control is used in a Sitecore site and I had forgotten to register the control type in the web.config file with a <typesThatShouldNotBeExpanded> entry. This entry is used to prevent server controls from having their events messed up by Sitecore - this can cause similar problems for standard server controls such as ListView, GridView and Repeater etc. My web.config was modified as shown below:
<typesThatShouldNotBeExpanded>
<type>System.Web.UI.WebControls.Repeater</type>
<type>System.Web.UI.WebControls.DataList</type>
<type>System.Web.UI.WebControls.GridView</type>
<type>MyNamespace.MyCustomControl</type> <!-- This is the bit I added -->
</typesThatShouldNotBeExpanded>
In my experience this sort of problem is usually due to not assigning an ID to dynamically generated controls.
LinkButton prevLink = new LinkButton();
prevLink.ID = "prevLink";
Apologies... this is not a complete answer, but a debugging suggestion that is too long for a comment:
In your browser save an HTML copy of your page for initial load, postback load, and second postback. Then compare the files using your favorite comparison tool. Eliminate obvious differences like search results, etc. This can help you pinpoint any issues with control IDs, missing controls, etc.
The two absolute keys to successful dynamically created controls are
1) Creating them at the correct time during the page lifecycle
2) Re-creating the EXACT SAME control hierarchy (including IDs) on postback
To get the proper control tree override the Controls property and call the EnsureChildControls, and also call the EnsureChildControls and not the CreateChildControls inside the PagerLinkCommand.
/// <summary>
/// Gets controls.
/// </summary>
public override ControlCollection Controls
{
get
{
EnsureChildControls();
return base.Controls;
}
}
/// <summary>
/// Create child controls.
/// </summary>
protected override void CreateChildControls()
{
this.Controls.Clear();
//do stuff here e.g.
LinkButton prevLink = new LinkButton();
prevLink.Text = "< Prev";
prevLink.CommandArgument = (PageIndex - 1).ToString();
prevLink.Command += new CommandEventHandler(PagerLinkCommand);
this.Controls.Add(prevLink);
}
protected void PagerLinkCommand(object sender, CommandEventArgs e)
{
PageIndex = int.Parse(e.CommandArgument.ToString());
EnsureChildControls();
}
The reason for this behaviour was not down to the server control itself, but was Sitecore-related. In order for Sitecore to not interfere with server control postbacks, it is necessary to add an entry under the typesThatShouldNotBeExpanded section in the web.config file as shown below.
<typesThatShouldNotBeExpanded>
<type>System.Web.UI.WebControls.Repeater</type>
<type>System.Web.UI.WebControls.DataList</type>
<type>System.Web.UI.WebControls.GridView</type>
<type>MyNamespace.MyCustomControl</type> <!-- This is the bit I added -->
</typesThatShouldNotBeExpanded>
I am trying to create a popup which will be used to select a month/year for a textbox. I have kind of got it working but however when I try and read from the textbox when I Submit the form it returns an empty string. However visually on the page I can see the result in there when I click the Done button which can be seen in the screenshot.
http://i27.tinypic.com/2eduttx.png - is a screenshot of the popup
I have wrapped the whole textbox/popup inside a Web User Control
Here is the code of the control
Code Behind
ASP Page
and then read from the Textbox on the button click event with the following
((TextBox)puymcStartDate.FindControl("txtDate")).Text
Any suggestions of how to fix the problem?
You may need to read the form posted value rather than the value from the view state. I have the following methods in my code to handle this.
The below code just grabs the values in the request headers (on post back) and sets/updates the controls. The problem is that when using the ASP.NET Ajax controls, it doesn't register an update on the control, so the viewstate isn't modified (I think). Anyways, this works for me.
protected void btnDone_Click(object sender, EventArgs e)
{
LoadPostBackData();
// do your other stuff
}
// loads the values posted to the page via form postback to the actual controls
private void LoadPostBackData()
{
LoadPostBackDataItem(this.txtYear);
LoadPostBackDataItem(this.txtDate);
// put other items here if needed
}
// loads the values posted to the page via form postback to the actual controls
private void LoadPostBackDataItem(TextBox control)
{
string controlId = control.ClientID.Replace("_", "$");
string postedValue = Request.Params[controlId];
if (!string.IsNullOrEmpty(postedValue))
{
control.Text = postedValue;
}
else
{
control.Text = null; // string.Empty;
}
}
I am using ASP.NET with C# 2.0 and Visual Studio 2005. I am using a Master page and content pages. I have a treeview menu in the master page and when a user selects any menu item I redirect to that content page.
My problem is that after a user navigates to the content page all the treenodes refresh and the structure is collapsed. I want the selected treenode to stay expanded.
Can anybody help me out?
When you refresh the treeview you want to call treeView1.ExpandAll();
Also add an event for the BeforeCollapse and set the event's Cancel property to true, to prevent the user from collapsing your treenodes.
private void treeView1_BeforeCollapse(object sender, TreeViewCancelEventArgs e)
{
e.Cancel = true;
}
Hope this helps.
-jeremy
This is a common enough problem that is automatically handled by ASP.NET if you use a SiteMapDataSource control as the datasource for your TreeView. In this case, you haven't mentioned what the Datasource of your TreeView is.
You also haven't mentioned if the TreeView contains links (the NavigateUrl property is set) or Text items that postback for each click. If it is the former, then as far as I know, you are out of luck! This is because none of the Selection events are raised for TreeNodes which have their NavigateUrl set. They just function as regular hyperlinks.
If however, it is the latter, then you can try out the following steps :
a. Handle the SelectedNodeChanged event of the TreeView. In this event handler, retrieve the current value of the SelectedNode.ValuePath property and store it in ViewState/Session. Use the Value of the of the SelectedNode to conditionally redirect the page to URL mapped to it.
Something like the following:
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
TreeNode selNode = TreeView1.SelectedNode;
string pathToNode = selNode.ValuePath;
Session.Add("SelPath", pathToNode);
switch (selNode.Value)
{
//Redirect to URL accordingly.
}
}
b. On subsequent load of the Master page (the page to which you redirected), retrieve the value of the ValuePath set earlier and find the previously Selected node and Expand it.
Something like the following:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
string pathToNode = (string)Session("SelPath");
Session.Remove("SelPath");
TreeNode selNode = TreeView1.FindNode(pathToNode);
if (selNode != null)
{
selNode.Expand();
}
}
}
Note that I haven't had an opportunity to test the code so this is mostly hypothetical.
Try using the OnTreeNodeDataBound event and the treeView.SelectedNode property
Also, might want to check how/ when you're binding your TreeView to it's DataSource. You might be rebinding it on IsPostBack which will re-render the tree.
The TreeView should maintain its nodes on PostBack.
Even though you are using a Master page, once the user navigates to the content page it is rendered as a new/different page. Because of the Master page the same treeview is loaded but not the same instance. You will need to store and load what nodes were expanded.
I have a page that dynamically creates multiple usercontrols on the page_init event, and adds it to a placeholder on the page.
The usercontrols themselves databind to a repeater on page_init to a collection of about 10 strings, which outputs a div for each item.
There's also a "view more" link button on the user control. When I click the "view more" button it databinds another collection to a second repeater, with even more divs.
The problem: After clicking "view more" on one of the usercontrols, if I click "view more" on another usercontrol, the "view more" data is lost on the first usercontrol. I suspect it's because I'm not re-adding the controls, so viewstate isn't re-loaded.
Anyone have any ideas or am I just way off on this one? Thank you.
Problem is you need to re-create the dynamic controls on each postback and recreate their viewstate. Take a look at this article Dynamic Web Controls, Postbacks, and View State
Stan is right.
When you click in the link a postback occurs and you lost everything
I ran across the same problem, my aproach was recreate the dinamics UserControls on every postback.
this article http://www.codeproject.com/KB/user-controls/DynamicUC.aspx shows a example, but i implement a diferent code like this:
my page have the following method which dinammicaly add the controls to an PlaceHolder.
private void AdicionarControlesDinamicamente(int idPergunta)
{
if (idPergunta > 0)
{
this.IdPerguntaAtual = idPergunta;
PerguntaAtual = new Pergunta(this.IdPerguntaAtual);
UserControl uc = LoadControl(PerguntaAtual.TipoResposta.CaminhoUserControl, PerguntaAtual.IdPergunta);
phResposta.Controls.Add(uc);
ViewState["ControlesDinamicosPerguntaCarregados"] = true;
}
}
note this line of code ViewState["ControlesDinamicosPerguntaCarregados"] = true;
i store an information tha says that the controls already have been added to page.
then a ovveride the CreateChildControls to recreate the controls
protected override void CreateChildControls()
{
base.CreateChildControls();
// CHeck if the controls have been added to page, case true, i call IncluirControlesDinamicamente() again
// The Asp.Net will look into viewstate and wil find my controls there, so "he" will recreate their for me
if (ViewState["ControlesDinamicosPerguntaCarregados"] != null)
if (Page.IsPostBack)
AdicionarControlesDinamicamente(this.IdPerguntaAtual);
}
I think this help you.
PS: Sorry my english.