How To Call Child user Control Events on Parent Pages - asp.net

I have two User Controls. And one aspx page which is loading the controls. Code is given Below
Home.aspx:
<%# Page Title="" Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="MYApp.Home" %>
<asp:Panel ID="pnlTabs" runat="server"></asp:Panel>
Home.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
base.LoadUserControl(UC_Tabs, pnlTabs);
}
Tabs.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="UC_Tabs.ascx.cs" Inherits="MyApp.UserControls.UC_Tabs" %> <asp:Button ID="btnPhotoTab" runat="server" Text="Photos" CssClass="tab_style" style="border-right:none;" onclick="btnPhotoTab_Click" />
<asp:Panel ID="pnlPhotos" runat="server"></asp:Panel>
Tabs.ascx.cs:
protected void btnActivityFeed_Click(object sender, EventArgs e)
{
Home HomePage = (Home)this.Page;
LoadUserControl("UC_PhotoSearch.ascx", pnlPhotos);
}
public Control LoadUserControl(string ControlName, Control Container)
{
Control UControl = null;
if (ControlName != null)
{
UControl = this.LoadControl("~/UserControls/" + ControlName);
UControl.ID = UControl.GetType().Name;
Container.Controls.Add(UControl);
}
return UControl;
}
UC_PhotoSearch.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="UC_PhotoSearch.ascx.cs" Inherits="MyApp.UserControls.UC_PhotoSearch" %>
<input id="txtSearch" name="txtSearch" type="text" runat="server" />
<asp:Button ID="btnSearch" runat="server" Text="Search" onclick="btnSearch_Click" />
<span id="PhotoSearchedData" runat="server"></span>
UC_PhotoSearch.ascx.cs:
protected void btnSearch_Click(object sender, EventArgs e)
{
//Photo Search Code here
}
The above is all my code.
Now I am loading the Tabs control on Home page and
Photo search Control on Tabs control
Now I click on Search Button But the
btnSearch_Click in not firing and even the page load event is also not firing.
How can I able to Access the btnSearch_Click event from home page.
If I used the following on Tabs control then the button click is working fine.
<%# Register Src=”UC_PhotoSearch.ascx” TagName=”PhotoSearch” TagPrefix=”uc1″ %>
<uc1:PhotoSearch ID=”PhotoSearch″ runat=”server” />
So what is wrong with dynamic loading of controls.
Please Help me

Not sure if I understand you quite, but I think if you load your controls in the Page's PreInit event and not Page_load your events will fire.

Related

Button not fired up inside asp user control used for umbraco macro

I'm searching solutions for my problem already since 2-3h and I decided better to ask.
I have created and empty web site and the installed umbraco, set up a new macro and it seemd ok but a button is not fired .
The code in Test.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Tests.ascx.cs" Inherits="Demo.Tests" %>
<h1>test</h1>
<form id="Form1" runat="Server">
<asp:Button ID="btnRunTest" OnClick="onClick_btnRunTest" Text="Run test" runat="server" CausesValidation = "false"/>
</form>
<div style="background-color: #de6363; padding: 10px;">
<asp:Label ID="lblMessage" runat="server" Text="" ForeColor="black" />
</div>
And code behind:
public partial class Tests : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
//btnRunTest.Click += new EventHandler(this.onClick_btnRunTest);
}
public void onClick_btnRunTest(object sender, EventArgs e)
{
lblMessage.Text = "";
Stopwatch stopwatch = Stopwatch.StartNew();
DynSLinkedList<int?> list = new DynSLinkedList<int?>();
list.Add(1);
list.Add(18);
list.Add(-1);
list.Add(-2);
list.Add(1);
list.Add(18);
list.Add(-1);
list.Add(-2);
list.Add(1);
list.Add(18);
list.Add(-1);
list.Add(-2);
list.Add(1);
list.Add(18);
list.Add(-1);
list.Add(-2);
list.Remove(18);
list.Remove(-2);
list.Remove(1);
var time = stopwatch.Elapsed.ToString();
lblMessage.Text = "Task finished in time "+time +"</br>";
}
}
When I hit the button page reloads but the onClick_btnRunTest is not hit

ViewState on programmatically loaded usercontrols (restored after Page_Load)

I'm trying to create a simple web page with a navigation bar and some usercontrols (ascx) programmatically loaded.
All controls are inside an update panel.
When I click on a link button (from the navigation bar) I do the following things:
I save the current usercontrol using viewstate.
Than I reload the current usercontrol.
My 'page_load' always reloads the current control.
Always assigning the same ID to the programmatically loaded control allows me to save the usercontrol viewstate.
So everything look good except one little thing: the usercontrol viewstate in not available during the usercontrol Page_Load!
Look below for (* HERE).
The 'txtTest.Text' value is always "0" (also during postback).
It seems that the user control viewstate is restored after the (usercontrol) Page_Load.
How is it possible?
--- "DEFAULT.ASPX": ---
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="sm" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="pnlMain" runat="server">
<ContentTemplate>
<div class="links">
<asp:LinkButton ID="lnkButton1" runat="server" OnClick="lnkButton1_Click" Text="Link 1"></asp:LinkButton>
<asp:LinkButton ID="lnkButton2" runat="server" OnClick="lnkButton2_Click" Text="Link 2"></asp:LinkButton>
</div>
<br />
<asp:Panel ID="pnlCtrl" runat="server"></asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
--- "DEFAULT.ASPX.CS": ---
private string CtrlAscx
{
get
{
if (ViewState["CtrlAscx"] == null)
{
ViewState["CtrlAscx"] = String.Empty;
}
return ViewState["CtrlAscx"].ToString();
}
set
{
ViewState["CtrlAscx"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
loadMyControl();
}
private void loadMyControl()
{
if (!String.IsNullOrEmpty(CtrlAscx))
{
pnlCtrl.Controls.Clear();
Control c = LoadControl(CtrlAscx);
c.ID = CtrlAscx + "ID"; // this line is mandatory in order to mantain the usercontrol viewstate
pnlCtrl.Controls.Add(c);
}
}
protected void lnkButton1_Click(Object sender, EventArgs e)
{
CtrlAscx = "Control1.ascx";
loadMyControl();
}
protected void lnkButton2_Click(Object sender, EventArgs e)
{
CtrlAscx = "Control2.ascx";
loadMyControl();
}
-- "CONTROL1.ASCX" --
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Control1.ascx.cs" Inherits="WebTest.Control1" %>
Control1: <asp:TextBox id="txtTest" runat="server" Text="0"></asp:TextBox>
<asp:Button ID="btnTest" runat="server" />
-- "CONTROL1.ASCX.CS" --
public partial class Control1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (txtTest.Text == "0") // * HERE
{
txtTest.Text = "1";
}
}
}
Try the EnableViewState="true" attribure on txtTest as well as on your custom user control when creating it :
.
.
c.EnableViewState = true;
pnlCtrl.Controls.Add(c);

Page Load not firing when input control placed in an asp GridView

I have a gridview which displays product information on the index page of my site for a user. I want to extend this to allow the user to tick a checkbox if they have reviewed a product.
However, after adding the check box column into my gridview template, when i try to search multiple times the Page_Load event of my index page stops firing, this causes an issue as some of the events further down the execution tree require the object that is initialised at page load.
The problem seems to be that placing any asp input control inside the gridview is somehow preventing Page_Load from firing before the DataSources OnSelecting and OnSelected and the Grids OnRowDataBound events but i can't see why.
Here is my sample code, I can't see what I'm doing wrong here.
Index.aspx.cs
private ProductSearch productSearch
protected void Page_Load(object sender, EventArgs e)
{
productSearch = new ProductSearch(GetSearchParameters());
productSearch.PageLoad()
}
protected void ProductsSelecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
e.InputParameters["searchParams"] = productSearch.GetSearchParams();
}
protected void ProductsSelected(object sender, ObjectDataSourceStatusEventArgs e)
{
productSearch.SetExportToCsvButton();
}
protected void ProductsPageIndexChanging(object sender, GridViewPageEventArgs e)
{
dgProducts.PageIndex = e.NewPageIndex;
}
protected void ProductsOnRowDataBound(object sender, GridViewRowEventArgs e)
{
productSearch.ProductsRowDataBound(e.Row);
}
Index.aspx
<%# Page Language="C#" MasterPageFile="~/Admin/AdminMaster.master" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="Web.Admin.Index" %>
<asp:Content ContentPlaceHolderID="DataFrame" runat="server">
<asp:GridView ID="dgProducts" runat="server" AllowPaging="True" AllowSorting="True" EnableViewState="False"
AutoGenerateColumns="False" DataSourceID="dsProducts" PagerSettings-Position="TopAndBottom" DataKeyNames="ProductNo, KitID"
OnPageIndexChanging="ProductsPageIndexChanging" OnRowDataBound="ProductsOnRowDataBound"
EmptyDataText="There are no products matching your search." meta:resourcekey="dgProducts" onrowcreated="ProductsRowCreated">
<HeaderStyle Font-Size="Small" />
<Columns>
<asp:TemplateField HeaderText="Reviewed">
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkReviewed" class="reviewedCheckbox" Checked="False" />
</ItemTemplate>
</asp:TemplateField>
</Columns
</asp:GridView>
<asp:ObjectDataSource ID="dsProducts" runat="server" EnablePaging="True" SelectMethod="ProductAndKitSearchByParams"
TypeName="ProductSearchController.ProductSearch" onselecting="ProductsSelecting" SortParameterName="SortParameter"
SelectCountMethod="SelectVirtualCount" OnSelected="ProductsSelected">
<SelectParameters>
<asp:Parameter ConvertEmptyStringToNull="true" DefaultValue="" Name="searchParams" Type="Object" />
</SelectParameters>
</asp:ObjectDataSource>
</asp:Content>
Check you master page contentplaceholderid and provide it in content page like this:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server"></asp:Content>
and also check your content page codebehind file name should be same as mention in page directives.

How do I load two ASP.NET UserControls on Demand?

I want load two user controls on demand.
asp:UpdatePanel ID="UpdatePanel1" runat="server"
ContentTemplate
asp:Button ID="Button1" runat="server" Text="Button" UseSubmitBehavior="false"
OnClick="Button1_Click" /
div id='Div_UserControlPlace' enableviewstate="true" runat="server"
/div
/ContentTemplate
Triggers
asp:PostBackTrigger ControlID="Button1" /
/Triggers
/asp:UpdatePanel
asp:UpdatePanel ID="UpdatePanel2" runat="server"
ContentTemplate
asp:Button ID="Button2" runat="server" Text="Button" UseSubmitBehavior="false"
OnClick="Button2_Click" /
div id='Div_UserControlPlace2' enableviewstate="true" runat="server"
/div
/ContentTemplate
aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Control FeaturedProductUserControl = new Control();
FeaturedProductUserControl = LoadControl("WebUserControl1.ascx");
FeaturedProductUserControl.EnableViewState = true;
Div_UserControlPlace.Controls.Add(FeaturedProductUserControl);
}
protected void Button2_Click(object sender, EventArgs e)
{
Control FeaturedProductUserControl2 = new Control();
FeaturedProductUserControl2 = LoadControl("WebUserControl2.ascx");
FeaturedProductUserControl2.EnableViewState = true;
Div_UserControlPlace2.Controls.Add(FeaturedProductUserControl2);
}
I load the first user control by clicking on the first button - this works properly but when I click on the other button to load the second UserControl, the first UserControl disappears and the second UserControl loads.
Thanks
IFA_User
You should use the Placeholder control to dynamically add your controls to the form.
Take a look at my last responses about dynamic controls:
OnClick event of dynamically created LinkButtons is not working
Dynamically Added DropDownlists Are Not Firing SelectedIndexChanged Event
Dynamically create an ImageButton
Now I already have some code working for demo purpose, each dynamic user controls keeps its state across post backs
This is the output:
ASPX
<asp:PlaceHolder runat="server" ID="addresses" /><br />
<asp:Button Text="Add Address" runat="server" ID="addAddress" OnClick="addAddress_Click" />
ASPX Code behind
protected void Page_PreLoad(object sender, EventArgs e)
{
for (int i = 0; i < this.DynamicControlsCount; i++)
{
var c = this.LoadControl("~/AddressControl.ascx");
this.addresses.Controls.Add(c);
}
}
protected void addAddress_Click(object sender, EventArgs e)
{
this.DynamicControlsCount++;
var c = this.LoadControl("~/AddressControl.ascx");
this.addresses.Controls.Add(c);
}
protected int DynamicControlsCount
{
get
{
if (this.ViewState["ac"] == null)
{
return 0;
}
return (int)this.ViewState["ac"];
}
set
{
this.ViewState["ac"] = value;
}
}
ASCX
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="AddressControl.ascx.cs" Inherits="WebApplication1.AddressControl" %>
<asp:Panel ID="Panel1" runat="server" GroupingText="Address" DefaultButton="btnSave">
Street: <asp:TextBox runat="server" ID="txtStreet" /><br />
City: <asp:TextBox runat="server" ID="txtCity" /><br />
<asp:Button Text="Save" runat="server" ID="btnSave" OnClick="btnSave_Click" />
</asp:Panel>
<asp:Panel runat="server" GroupingText="Address Summary" Visible="false" ID="summary">
<asp:Label ID="lblStreet" runat="server" /><br />
<asp:Label ID="lblCity" runat="server" />
</asp:Panel>
ASCX Code behind
protected void btnSave_Click(object sender, EventArgs e)
{
this.summary.Visible = true;
this.lblCity.Text = "Selected city: " + this.txtCity.Text;
this.lblStreet.Text = "Selected street: " + this.txtStreet.Text;
}
When a user control is created in the HTML, asp.net will persist across postbacks without any user interaction. But if you are loading them programatically (dynamically), they will not persist accross postbacks. So if you load them programmatically, you have the added task of persisting them programmatically as well. Use the ViewState (or Session I suppose) to store what has been loaded and perhaps any other necessary information that needs to be loaded between postbacks. Every single postback will require you to reload every control or else they will disappear.
There are couple of ways of doing it:
U can load the UserControls using Ajax. Benefit of using Ajax, is ur page does not get post back, thus for example, on click event of Button1, call a ajax(traditional/Jquery) to load UserControl1, and on button click of Button2 User control2.
Put the two button in two different updated panel, by doing this the click event will only refresh a part of ur page.
U have to save somewhere (ViewState/Session),which buttons are clicked, and upon clicking of any button check the value of that variable, and explicit load the control.
Points to note - If u want to get ur data back when ur page made a complete postback, then u have to add the controls keeping in mind the Page load event cycle.

ASP.NET page with base class with dynamic master page not firing events

I am feeling that I have terribly wrong somewhere. I was working on a small asp.net app. I have some dynamic themes in the \theme folder and have implemented a page base class to load the master page on the fly. The master is having the ContentPlaceHolder like:
<asp:ContentPlaceHolder ID="cphBody" runat="server" />
Now I am adding pages that are derived from my base class and added the form elements. I know, Visual Studio has problem showing the page in the design mode. I have a dropdown box and wish to add the event of onselectedindexchange. But it is not working. the page is like this:
<%# Page Language="C#" AutoEventWireup="true" Inherits="trigon.web.Pages.MIS.JobStatus" Title="Job Status" AspCompat="true" CodeBehind="JobStatus.aspx.cs" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cphBody" runat="Server">
<div id="divError" runat="server" />
<asp:DropDownList runat="server" id="jobType" onselectedindexchange="On_jobTypeSelection_Change"></asp:DropDownList>
</asp:Content>
I have also tried adding the event on the code behind like:
protected void Page_Load(object sender, EventArgs e)
{
jobType.SelectedIndexChanged += new System.EventHandler(this.On_jobTypeSelection_Change);
if (!IsPostBack)
{
JobStatus_DA da = new JobStatus_DA();
jobType.DataSource = da.getJobTypes();
jobType.DataBind();
}
}
protected void On_jobTypeSelection_Change(Object sender, EventArgs e)
{
//do something here
}
Can anybody help?
Regards,
set AutoPostBack="true" on your dropdown

Resources