ASP.Net User Control not working when added at run time - c#

I have simply created a user control in asp.net which has a textbox,calendar and a button.
On the click event of that button i am making the calendar visible,and on the calendar's onselectionchanged event i am passing the selected date to the textbox.
Now i have a .aspx page in which i am adding this user control at RUN TIME.
The user control gets added,but the click event of the button by which i am making the calendar visible is not getting fired.
What is the Issue? Its working fine when i add that user control at design time.
But when i add it at run time in not working.
<%# Control Language="C#" AutoEventWireup="true" CodeFile="Dates.ascx.cs" Inherits="Date"%>
//created a public object named 'users' of control class
public partial class View_now : System.Web.UI.Page
{
public Control users;
}
//loaded the user control in page load event
protected void Page_Load(object sender, EventArgs e)
{
users = LoadControl("~\\Dates.ascx");
}
//applied the user control to a panel
protected void Button2_Click(object sender, EventArgs e)
{
Panel2.Controls.Add(users);
}
Now when i click the usercontrol's button,the click event doesn't fire.

Add the controls during Page_Init() not Page_Load(). That should do the trick.

Related

Dropdownlist in masterpage is not returning a default value that was set by content page

I have a DropDown bound to a data source. And has auto-postback to true so that I can call middle-tier based on the value selected. But, by default, the second value in the dropdown is selected by the content page in the page load event. But a method on the content page doesn't get the selected value.
<asp:DropDownList ID="ddlStatuses" runat="server" DataSourceID="dsStatus" AutoPostBack="true" Enabled="false" Visible="false"
DataTextField="Description" DataValueField="StatusId" OnSelectedIndexChanged="ddlStatuses_SelectedIndexChanged">
</asp:DropDownList>
In master page code-behind, I have the following methods to get, set the status.
public delegate void StatusHandler(object sender, EventArgs e);
public partial class MasterPageTest: System.Web.UI.MasterPage
{
public event StatusHandler StatusChanged;
protected virtual void OnStatusChanged(EventArgs e)
{}
public int SelectedStatus()
{
return ddlStatuses.SelectedValue.ToInt();
}
public bool ShowStatusDDL
{
get { return ddlStatuses.Visible; }
set { ddlStatuses.Enabled = ddlStatuses.Visible = value; }
}
public void SetSelectedStatusDDL()
{
ddlStatuses.SelectedValue = Statuses.Unread.ToString();
}
protected void ddlStatuses_SelectedIndexChanged(object sender, EventArgs e)
{
if (StatusChanged != null)
{
StatusChanged(this, e);
}
}
}
The content page sets the default Status in the dropdown on page load and then try to call a method to pass the selected value to middle tier. This is where the problem is - on load it doesn't get the default value, but on dropdown change, it works as expected.
protected void Page_Load(object sender, EventArgs e) {
Master.StatusChanged += Master_StatusChanged;
if(!IsPostBack) {
Master.ShowStatusDDL = true;
Master.SetSelectedStatusDDL(); //Setting the status to say 2nd item in the list
MainFunctionality();
}
private void MainFunctionality()
{
var statusId = Master.SelectedStatus(); // This doesn't show the selected status but blank
//Some more code that passes the statusId to the middle tier
}
Why won't it get the default value, I am sure there is something silly that I am not seeing. But, I already spent hours in it to debug.
Here is a little more background:
Originally, I had an ObjectDataSource in content page aspx that loads the results in the GridView, and the following event dsMessages_Selecting reads the Master.SelectedStatus() to pass it to the data source to get the filtered data. And this event was able to read the selected dropdown value. I removed that object data source to write my own in the code behind on page load. Now, the selected dropdown doesn't work. Although content page load sets the default value, but there is some other event that I am missing that makes sure the value is selected.
I resolved the issue, for other's who might get into this issue in the future and spend a lot of time understanding the problem, I am posting the solution.
The issue was with the way events were firing, thanks to #VDWWD for making me think about how events are getting fired.
I had a code in the content page_load event that was setting the dropdown default selection and followed it with the code that would load the grid using the selected value.
protected void Page_Load(object sender, EventArgs e) {
Master.StatusChanged += Master_StatusChanged;
if(!IsPostBack) {
Master.ShowStatusDDL = true;
Master.SetSelectedStatusDDL(); //Setting the status to say 2nd item in the list
MainFunctionality();
}
}
This grid was not filtering the data based on the selection, because the content page_load didn't know about the selection somehow, I would assume that gets updated later in the event lifecycle.
So I moved that MainFunctionality() from content page_load to content gridview_PreRender to delay the call to find the selected dropdown value. Since this is almost the last event that fires before the unload event, I thought by then I will get the selected dropdown value. And, it worked exactly how I wanted it to work.
The following is the sequence in which events occur when a master page is merged with a content page for your reference:
Content page PreInit event.
Master page controls Init event.
Content controls Init event.
Master page Init event.
Content page Init event.
Content page Load event.
Master page Load event.
Master page controls Load event.
Content page controls Load event.
Content page PreRender event.
Master page PreRender event.
Master page controls PreRender event.
Content page controls PreRender event.
Master page controls Unload event.
Content page controls Unload event.
Master page Unload event.
Content page Unload event.
From Microsoft Documentation

Button not firing in user control

I currently have a master page that has a drop down menu which displays a different User control depending on the menu choice.
Inside of the User control I'm trying to add a submit button that processes the inputted forms inside the user controls using the "_Click()" event handler. My user control aspx looks like the following:
<asp:Button ID="configBttn" runat="server" OnClick="configBttn_Click" AutoEventWireUp="true" />
and then I have the following in the codebehind:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void configBttn_Click(object sender, EventArgs e)
{
Response.Write("Hello world");
}
I have even tried to add an event handler:
configBttn.Click += new EventHandler(configBttn_Click)
However this is still not allowing for the button to be triggered. Any ideas?
I add the user control inside the codebehind inside a div container:
divContainer.Controls.Add(pPage.LoadControl("~/Controls/Control.ascx"));
Where are you creating the UserControl in the Page Lifecycle?
I suspect that it needs to be created in the Init method of its container page.
In addition, they should not be wrapped in a !IsPostback block, or else when the page posts back, the control event handler is not mapped, so nothing is there to catch the click event.
Without seeing the code that adds the user control, I'm guessing that it is not saved as part of the page's view state. Which means when you click the button inside the user control the whole page gets refreshed and the user control is either not created or a different instance of it is created.

onClick event is not working for user control controls

I'm loading an user control in one of the class file. This is not code behind page. This is common class for grid view which is applied to all the gridviews in all pages.
I added onclick method to the controls in the user control, but they are not firing in the code behind of that user control.
I kept break points. However, it is not reaching those break points. In addition, the user control is getting closed after I click on any control which has onclick method. After clicking the entire page is reloading in which the grid view is loaded and because of it i guess user control is disappearing. I used update panel in user control still it is not working. Onclicking the the user control is going inside on_pageload of that user control.
This user control is displayed when an image on each column of grid header is clicked. My code is as follows
User control ASCX:
<asp:LinkButton ID="lnkSortDescending" runat="server"
onclick="lnkSortDescending_Click">
Sort Descending
</asp:LinkButton>
Code Behind:
protected void lnkSortDescending_Click(object sender, EventArgs e)
{
//some code
}
File in which user control is loaded:
protected void btnFilterButton_Click(object sender, ImageClickEventArgs e)
{
int i = 0;
Panel p = new Panel();
Control uc = (Control)Page.LoadControl("~/UserControls/FilterPanel.ascx");
uc.ID = "Filter"+(i++);
p.Controls.Add(uc);
}
Please help me to solve this problem.

How do I get my asp:Button to execute code in the OnClick event?

First off... I'm a noob to both ASP.net and C#. I'm updating a page that already exists to add a button..
My code..
<div style="padding: 10px;float: left;"><table><tr><td><asp:Button id="DoSomething" Text="Build Patch" runat="server" OnClick="DoSomething_click" /><br /></td></tr></table></div>
This lives in my ascx control... the code behind is...
protected void DoSomething_click(object sender, System.EventArgs e)
{
Response.Write("<script> alert('Hi');</script>");
}
It gets wired up on the default.aspx page in
<%# Register Src="~/ui/MyView.ascx" TagName="MyView" TagPrefix="UC" %>
and is used in a asp:repeater...
<UC:MyView PB=<%# Container.DataItem %> runat="server"></UC:MyView>
The repeater creates the buttons inside a <td>
I supose my question is how do I wire up the onclick for these buttons? I debug and my DoSomething_click method never hits.
Basically you need to pass your ButtonClick event from UserControl to your webpage ( that contains this userControl). This is known as Bubble up of events
User control portion:
Define your OnClick event for the Button. However, in this event you will pass this to your .aspx page.
public partial class MyView : System.Web.UI.UserControl
{
public event EventHandler SomethingButtonClick;
protected void DoSomething_Click(object sender, EventArgs e)
{
//pass the event up to the aspx page. also called bubbling up the event.
if (this.SomethingButtonClick != null)
this.SomethingButtonClick(this, e);
}
}
Your page containg the UserControl:
Set the event handler for SomethingButtonClick event in Page_Init() event as :
protected void Page_Init(object sender, EventArgs e)
{
MyView1.SomethingButtonClick += new EventHandler(MyView_SomethingButtonClick);
}
Add/Define this MyView_SomethingButtonClick in your page code behind itself.
protected void MyView_SomethingButtonClick(object sender, EventArgs e)
{
//handle the event
Response.Write("<script> alert('Hi');</script>");
}
First off, try specifying type="text/javascript" inside of your script tag:
<script type="text/javascript">alert('hi');</script>
Assuming that doesn't work:
If I understand correctly, you are trying to link the dynamically created button to the code in the codebehind. This can get very, very weird. I would recommend using a "proxy function" of sorts. Create a javascript function elsewhere on the page that gets called by the button(s)' click event. This javascript function can then initiate a postback from there. I'll see if I can find the example I've used elsewhere.
EDIT: I can't find my original example, but this is a good reference: ASP.NET postback with JavaScript
Please note that the __doPostBack() function has TWO underscores, not one.

There has to be a way to get my data bound at the correct time

Say aspx page called theParent has a DataGrid control named theDataGrid and a UserControl named theUserControl , and theUserControl has a button named theUcButton .
Yes, I know, very imaginative naming.
When theUcButton is clicked , a session variable is changed.
This session variable is a select parameter for the datasource of theDataGrid.
However, because of the order of stuff called in the page lifecycle, when theUcButton is clicked and a postback is generated ,
theParent controls are loaded before theUserControl resets the session variable, and theDataGrid does not show the new data until the next postback .
How to I get what I want to work?
I am using 3.5 if that matters.
Here is example code for your user control to raise an event.
public partial class WebUserControl : System.Web.UI.UserControl{
public event EventHandler Updated;
protected void Button1_Click(object sender, EventArgs e)
{
//do some work to this user control
//raise the Updated event
if (Updated != null)
Updated(sender, e);
}}
Then from your .aspx page, you'll deal with the new event just like usual
<uc1:WebUserControl ID="WebUserControl1" runat="server" OnUpdated="WebUserControl1_Updated" />
Code behind:
protected void WebUserControl1_Updated(object sender, EventArgs e)
{
//handle the user control event
}
You can declare an event as a member of the UserControl class, raise it, and handle it in the Page class.
You can also use other events like Page.PreRender() to pick up things after the user control's events.
The easiest way would be to hold off on the databind until the later in the lifecycle, such as the Page.PreRender event as joelt suggested. If you do the bind then, you should have the session variables.

Categories

Resources