i'm a beginner in .NET, and search since yesterday morning to resolve my problem without finding the solution.
Here is my problem :
I create dynamically some User Controls by this way, because I need to give parameters :
List<ANNOUNCEMENT> listAnnouncement = getAnnoucements();
foreach(ANNOUNCEMENT ann in listAnnouncement)
{
if(ann.IS_CURRENT_ANNOUNCEMENT && currentAnnouncement == null)
{
currentAnnouncement = ann;
}
List<Object> listParams = new List<Object>();
listParams.Add(ann);
AnnouncementPresentation ap = (AnnouncementPresentation)(Controller.LoadControl(Page, "~/UserControls/AnnouncementPresentation.ascx", listParams.ToArray()));
/* important for the end of the method */
ap.modifyAnnouncementButtonClick += new EventHandler(modifyAnnouncementButtonClick);
pnl_announcements.Controls.Add(ap);
}
In this ASCX, I have a button, and when user will click on it, I want to call a method contained in my ASPX, so I do this in the ASCX :
public event EventHandler modifyAnnouncementButtonClick;
protected void btn_modify_announcement_Click(object sender, EventArgs e)
{
PageAdminAnnonces.currentAnnouncement = annonce;
modifyAnnouncementButtonClick(sender, e);
}
And this in the ASPX :
protected void modifyAnnouncementButtonClick(object sender, EventArgs e)
{
initListOfAnnouncement();
lbl_errors.Text = currentAnnouncement.TITLE;
}
I think everything works, but there is the problem : It works once, and at the end of the method, I delete my ASCX as you can see, and create new ASCX. But they don't have the methods, and when I click again, nothing works, so the ASPX is reloaded. After reloading, it works again.
Do i do something wrong?
According to the information in the comments, I suppose that your solution does not work because you are recreating the controls in the Click event handling method, which is very late in the page's lifecycle and should not be used for adding controls.
As mentioned in the comments, I suggest you to create the controls in Page_Init or Page_Load and not recreate them in the button's Click handling method. You should also assign a unique ID to each of them. Then, in the Click handler, you can use FindControl method to acces the created controls. Alternatively you can just save the references to the controls upon creation, so you can access them later easily.
Useful links:
http://msdn.microsoft.com/en-us/library/ms178472.aspx
http://visualstudiomagazine.com/articles/2010/10/11/more-on-adding-controls-dynamically.aspx
Related
I made researching about this subject I could not find proper answer.
In my default.aspx page, I have a treeview. Codes are in default.aspx like below:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
Control ucont;
if (TreeView1.SelectedNode.Value == "Yeni Dönem")
{
ucont = LoadControl("usercontrols/yenidonem.ascx");
PlaceHolder1.Controls.Add(ucont);
}
else
{
ucont = LoadControl("usercontrols/tabloktar.ascx");
PlaceHolder1.Controls.Add(ucont);
}
}
I load user controls dnynmicaly. User controls are have button control. I can not fire user control's button click when I load it dynamcally. How can I solve this ?
Thanks.
First of all, I would not recommend adding control dynamically later than in Page_Load event. Other things to remember is that You should add it on each page load and assign unique ID value the control that does not change between postbacks.
In this case, the easiest way would be to always add both controls to the page and show appropriate one using Visibility property.
If that's not suitable for You, try to move the code from TreeView1_SelectedNodeChanged to the Page_Load event and load appropriate control on each postback until it should be changed to another one.
I haven't tested this, so if You have any issues when using thise answer, let me know in the comments and I'll try to help.
I have a user control (Navigation) nested within another user control (Header) that is dynamically loaded from a Control class (Standard).
The user controls, Navigation and Header have AutoEventWireup = false.
The control class Standard calls loads the Header user control from a configuration item.
private void layoutAndRender(HtmlTextWriter output, string UserControlKey, NameValueCollection UserControlsConfiguration)
{
if(UserControlsConfiguration[UserControlKey] != null && UserControlsConfiguration[UserControlKey].ToString() != "")
{
string suc = System.Web.HttpContext.Current.Request.ApplicationPath + UserControlsConfiguration[UserControlKey].ToString();
UserControl ucToRender = (UserControl)this.Page.LoadControl(suc);
ucToRender.RenderControl(output);
}
}
My problem is that I want to initialize an object in the Navigation user control that can accept Page.Request and Page.Response, but events don't seem to be firing in the Navigation code behind.
The code I'm using to initialize my object is:
this.browser = new Browser(this.Request, this.Response);
I tried doing this during the Navigation constructor but this.Request and this.Response are not set at that time.
I tried using the statement in a void Page_Load(object sender, System.EventArgs e) method, but this doesn't seem to be firing, even if I have this.Load += new System.EventHandler(this.Page_Load); in the Navigation constructor.
I've also tried similar statements for Page_Init and Page_PreRender, but none of these seem to be firing.
Is it that a control loaded with LoadControl does not fire Load or Init events, if loaded the way I have loaded them, and the same goes for any user controls that it may include?
If AutoEventWireup is set to false for the controls that you want to load, then you should override the OnInit method to wire up the Load event handler for the controls. The Request and Response properties should be available from within Page_Load.
For example:
public class Header : Control
{
private void Page_Load(object sender, EventArgs e)
{
}
override protected void OnInit(EventArgs e)
{
this.Load += new System.EventHandler(this.Page_Load);
}
}
See MSDN for more info on AutoEventWireup:
http://support.microsoft.com/kb/324151
Unfortunately, this is legacy code, and not always done the right way.
In particularly, because the user control is loaded and rendered manually, it probably skips most of the event model that I wanted to take advantage of. Ideally, it should have done an AddControl() to the page, rather than rendering the control to a HtmlTextWriter.
My work around is to override the RenderControl method, and initialize the browser property before passing RenderControl up the chain.
I have a dropdown list in User Control
How Can I get selected value of dropdown list of user control in page when user select another item (auto postback is true)?
I tried to store selected value of ddl in a public member from Selected Index Changed event handler. But this handler executes after page load of container page. I need to load data in page based on selected value in ddl of user control.
Thanks
User Control's code
protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
{
_SelectedPageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
}
int GetSelectedPageSize()
{
return _SelectedPageSize;
}
There are a number of ways to accomplish what you're looking for. The first is simply to re-order your events in the containing page. If you use the PreRender event rather than the PageLoad event, your drop down selection action will be complete and the information will be readily available.
A second method, which probably more extensible, would be to raise a custom event from your usercontrol that your page listens for and handles. Then the action would be taken directly at the point where the information is immediately available. This allows any containing structure (whether it's a page, usercontrol or something similar) to subscribe to the event and handle whatever is needed.
A third method, a little more rigid, would be to have a function in the containing page that is called by the usercontrol once the data is complete. This requires the usercontrol to have knowledge of the specific page type that it will be included in (making it less extensible) so I wouldn't recommend it.
Edit: Here's an idea for implement option #2 with a custom event:
public partial class MyUserControl: UserControl
{
//All of your existing code goes in here somewhere
//Declare an event that describes what happened. This is a delegate
public event EventHandler PageSizeSelected;
//Provide a method that properly raises the event
protected virtual void OnPageSizeSelected(EventArgs e)
{
// Here, you use the "this" so it's your own control. You can also
// customize the EventArgs to pass something you'd like.
if (PageSizeSelected!= null)
PageSizeSelected(this, e);
}
private void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
{
_SelectedPageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
OnPageSizeSelected(EventArgs.Empty);
}
}
Then in your page code you would listen for the event. Somewhere in the page load you would add:
myUserControlInstance.PageSizeSelected += MyHandinglingMethod;
And then provide the method that handles the event:
protected void MyHandlingMethod(object sender, EventArgs e)
{
// Do what you need to do here
}
I have problem passing a variable from a main page containing a user control to the user control itself. Although the passed variable is available generally in the code-behind of the user control the page_load event can't seem to read it.
My code -
In the main page code-behind:
protected void FindCCFsButton_Click(object sender, EventArgs e)
{
if (CustomerDropDown.SelectedIndex != 0)
{ SearchUcCCFList.SetCustID(CustomerDropDown.SelectedValue); }
}
(SearchUcCCFList is the instance of the user control in the main aspx page).
In the user control code behind:
public partial class ucCCFList : System.Web.UI.UserControl
{
public string srchCust { get; set; }
public void SetCustID(string custID)
{
srchCust = custID;
testCustLabel.Text = GetCustID(); //this works
}
public string GetCustID()
{
return srchCust;
}
protected void Page_Load(object sender, EventArgs e)
{
CCFGridView.DataSource = DAL.SearchCCFs(custID : GetCustID()); //doesn't work
CCFGridView.DataBind();
test2CustLabel.Text = GetCustID(); //doesn't work
}
In the Page_Load event GetCustId() doesn't return anything (so the records aren't filtered and all get returned) although it can be read in the methods outside the Page_Load.
I'm probably making a beginners error but any help would be appreciated.
Edit - following Alan's suggestion in the comments I stepped through the page loading sequence & it appears that the user control's Page_Load event is running BEFORE the code in the main page's button click so the variable is not yet available. The sequence after clicking the button is:
User control Page_Load runs
Code in button event on main page
Other code (outside Page_Load) in user control runs hence variable is available here.
This seems a bit weird, is there another way to pass the variable into the user controls Page_Load?
In this case, your click handling even on the main page is called after the user control page load call. Your variable is being set, but not until after your data binding in the user control.
Either switch the user control to declarative binding which will handle calling methods in the correct order for you. Or the easier fix in this case is to change the user control data binding from Page_Load to Page_PreRender, which is called later in the life cycle, after the main page click handling call.
protected void Page_PreRender(object sender, EventArgs e)
{
CCFGridView.DataSource = DAL.SearchCCFs(custID : GetCustID()); // will work now
CCFGridView.DataBind();
test2CustLabel.Text = GetCustID(); // will work now
}
For a more thorough answer, read up on the ASP.NET page life cycle including the interaction with user controls' life cycle.
In the MSDN page lifecycle reference it states that the pre-init is used to "Create or re-create dynamic controls."
However, elsewhere on MSDN, an example implies that a dynamic user control should be loaded in Page_Load
Is this a contradiction? Or is pre-init used only for standard aspx controls?
What have I missed :)
Edit:
Either way works, however, there is presumably some benefit of one approach over the other.
(WebUserControl1 is a UserControl with a simple label property, SomeProperty)
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
WebUserControl1 wc1 = LoadControl(#"~\WebUserControl1.ascx") as WebUserControl1;
wc1.SomeProperty = "Hello World";
Controls.Add(wc1);
}
protected void Page_Load(object sender, EventArgs e)
{
WebUserControl1 wc1 = LoadControl(#"~\WebUserControl1.ascx") as WebUserControl1;
wc1.SomeProperty = "Hello World";
Controls.Add(wc1);
}
What exactly are you trying to do? Are you trying to pass information to the user control? If so you can pass the information to the user control in the page_load event from the parent page.
The answer is it depends on your custom control. If your user control doesn't need anything to happen before page_load, then you can go ahead and add your control during page load, if you have code in your user control that executes at an earlier time, then you should add your control at an earlier stage as the MSDN article suggests.