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.
Related
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 need a field to store some information after one asp button click for another asp button's click.
I saw that it wasn't working so I wrote the following simple page codebehind (thinking that perhaps some of my code was causing it) but here I can see that the field really does get re-initialized.
I suppose that every button click reloads the page. Is this true? And if so - how can this be overcome without a static variable (-because what if more than one person is accessing the same page at once...)?
public partial class _Default : System.Web.UI.Page
{
string s = "a";
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
s = "b";
}
protected void Button2_Click(object sender, EventArgs e)
{
here.InnerText = s;// "here" is an id.
//returns "a" despite Button1 having been clicked before.
}
}
add in your code (EnableViewState)
Each time you request (get or post) a page, a new instance of the _Default class (derived System.Web.UI.Page) is created (and then destroyed), the same happens with the contained controls.
See the ASP.NET Page Life Cycle.
When an ASP.NET page runs, the page goes through a life cycle in which
it performs a series of processing steps. These include
initialization, instantiating controls, restoring and maintaining
state, running event handler code, and rendering. It is important for
you to understand the page life cycle so that you can write code at
the appropriate life-cycle stage for the effect you intend.
You can persist a value (in your case the value of the field s) with different techniques (cookie, session, cache, viewstate, ...), see also ASP.NET State Management Overview.
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
I've written a custom widget to allow a user to select a location from a database of locations. This is my first ASP.net custom control. It seemed like everything was working fine, but now there's a problem.
My control implements the RaisePostBackEvent function as follows:
public void RaisePostBackEvent(string eventArgument)
{
SelectedLocationId = eventArgument.Split('|')[0];
SelectedLocationDescription = eventArgument.Split('|')[1];
}
I wrote a test page and included the following in my ASP code:
<%= locationSelector.SelectedLocationId %>
That worked fine.
However, in my web application, the following code does not work:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
Response.Write(locationSelector.SelectedLocationId);
// SelectedLocationId is null here!!!
}
When I run this code in the debugger, I see that my Page Load event fires before the Post Back event! Therefore, the data is not yet read from the postback. I know that using the MS provided text field control, the text is available at Page Load, so I think I must be doing something wrong.
How can I read the location that the user selected when the Page Load event fires? To clarify, I'm refering to the Page Load of a web application page.
You're setting SelectedLocationId on a postback event and at the same time you are trying to retrieve its value on the first load. SelectedLocationId will be null all right.
Try:
protected void Page_Load(object sender, EventArgs e)
{
if (locationSelector != null)
Response.Write(locationSelector.SelectedLocationId);
}