Add Event to Control added dynamic - c#

I'm using asp.net and c# for webForm. I'm generating a dropDownList dynamically, but I can't execute an event for this control. Below some code:
DropDownList nuevoCmb = new DropDownList();
nuevoCmb.ID = "ddl" + num;
nuevoCmb.Items.Add("---Seleccione el Plazo---");
nuevoCmb.Items.Add("Corto Plazo");
nuevoCmb.SelectedIndex = 0;
nuevoCmb.AutoPostBack = true;
nuevoCmb.SelectedIndexChanged += new EventHandler(nuevoCmb_OnSelectedIndexChanged);
MainPanel.Controls.Add(nuevoCmb);
protected void nuevoCmb_OnSelectedIndexChanged(object sender, EventArgs e)
{
string temp = "";
}

You need to add the code that creates the control to every page request, including postbacks. If the control causes a postback and the code that recreates the control is not called, your event handler will not fire. .NET will eventually call your event handler once a control with the same ID is added during the page load.

You should add dynamically added controls in or before the page Init event. It also works if you add during page Load event. After the Load event, your custom control events bubble up and fire. So if you're adding controls dynamically, they have to be added on each post back, being loaded before the page Load event ends, at the latest.

I found an answer in the follow page: Creating Dynamic DropDownList Controls in ASP.Net
This example is fully functional, but only an asp html page, is not working using master page. Any suggestion!

Related

UserControl DropDownList loses its selection

I have a user control with a DropDownList with AutoPostBack = true, also I have an aspx page to display this control.
I re-create user control in OnInit method of the page
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
var list = (List<Control>)Session[Controls];
if (list != null)
{
foreach (var control in list)
{
var uc = (Control)LoadControl(ControlPath);
uc.SetDropDownState(control.state);
PlaceHolderQuestion.Controls.Add(uc);
}
}
}
So while re-creating I am restoring DropDown selection, it works for the first time, but when I change selection again, OnSelectedIndexChanged event does not fire and it is obvious because I first restore DropDown selection in OnInit and so no OnSelectedIndexChanged event, cause nothing was changed, can you suggest some workaround?
UPDATE
var uc = (Control)LoadControl(ControlPath);
is required to be keep user controls events
After a deep research, I figured out that the issue was in the SelectedIndexChanged event logic.
I am using "Indirect Subscription" approach to handle it within my Page logic,
for more info please take a look
Indirect Subscription Approach
Originally I was reloading controls inside the handler but it was not required since I am doing it in the Page_Load method as well, so all I need to do is to update control inside my PlaceHolder controls list.
I hope it is clear, if not, please ask, and I will provide more description.

dynamically added buttons not firing click event c# [duplicate]

This question already has answers here:
dynamically created button click event not firing
(5 answers)
Closed 8 years ago.
I have some buttons that are being dynamically added to an asp.net page. However the onclick event is not being fired. Here is the code for it being added and it is ran when the page loads. I am very new to ASP.NET so I am sure I am making some basic errors. TIA.
protected void Page_Load(object sender, EventArgs e)
{
FillTable();
string rownum = (goalstable.Rows.Count).ToString();
Button bt = new Button();
bt.Text = "View";
bt.ID = (rownum);
bt.CssClass = "button";
bt.Click += Viewbutton_Click;
goalstable.Rows[1].Cells[0].Controls.Add(bt);
}
FillTable() is a method that fills a table from an SQL DB.
The on click event for the button that has been added.
protected void Viewbutton_Click(object sender, EventArgs e)
{
getGID();
setGoalDets();
goals.Style.Add("display", "block");
darkLayer2.Style.Add("display", "block");
}
Any Ideas what I may be doing wrong.
In a nutshell, you need to add the button earlier in the Page lifecycle, before the Page_Load event.
What's happening is every server event — even simple button clicks — is a new HTTP request to your page. In turn, every HTTP request for your page results in a completely new-from-scratch C# page object. Therefore you start with a brand new Page object and a brand new ViewButton when the click event for your ViewButton is triggered.
To make things work correctly, so the new page has the same properties as the old, ASP.Net relies on a feature called ViewState. ViewState information is (typically) submitted with the http request from the client's browser, and is used to build a new Page object with the same Controls and property values as the old one.
Here's the trick: ViewState is restored for the page before the load event is processed. If the button does not exist yet at the time the ViewState is restored, that information is thrown away, and the page will not later know it needs to raise the click event (or rather, it will think there there is no button for the click event code to run in the first place).
Therefore, you need to move the code to create your button to the Pre_Init event, which runs before the ViewState is restored.
When working with "dynamic" controls in ASP.Net WebForms, I often find it easier to just add a reasonable number of controls to the page in a static manner and set them all so that their Visible property is false. Then at runtime I will set Visible back to true for just the controls that I need.

User control not displayed after postback

I have a home.aspx page, where i have two panel. In first panel I have dynamically bound a User Control (for displaying meiny at left side) and in second I have displayed pages.
I bound user control dynamically at page load like.
if (!IsPostBack)
{
UserControl uc = (UserControl)Page.LoadControl("~/settings/Links/Navigation.ascx");
Accordion1.Controls.Add(uc);
}
when page first time loaded my usercontrol is bind and my menus are displayed, but when I clicked on any menu item it hides(user control),
Please help me, thanks in advance!
Put this line of code on Page_Init event of Page life cycle.
UserControl uc = (UserControl)Page.LoadControl("~/settings/Links/Navigation.ascx");
Accordion1.Controls.Add(uc);
Proper way:
protected void Page_Init(object sender, EventArgs e)
{
//MyControl is the Custom User Control with a code behind file
MyControl myControl = (MyControl)Page.LoadControl("~/MyControl.ascx");
//UserControlHolder is a place holder on the aspx page where I want to load the
//user control to.
UserControlHolder.Controls.Add(myControl);
}
If you use if (!IsPostBack) then after postback it will not be added to the page. At the first time you will be able to see the control on the page.
Reference:
ASP.NET Custom user control to add dynamically
How to: Create Instances of ASP.NET User Controls Programmatically
It's a dynamic control which must be recreated and readded to the page on every postback.
So this will work:
//if (!IsPostBack)
//{
UserControl uc = (UserControl)Page.LoadControl("~/settings/Links/Navigation.ascx");
Accordion1.Controls.Add(uc);
//}
For Dynamic control there is no need for !IsPostBack Property of page, Remove this property and use
UserControl uc = (UserControl)Page.LoadControl("~/settings/Links/Navigation.ascx");
Accordion1.Controls.Add(uc);
It must be loaded on each postback. keep the user control loading code outside if(!IsPostBack){}.

loading usercontrols dynamically - postback issue

Im trying to load a usercontrol dynamically on a aspx page however it works but i get postback issues?? I have a image button on usercontrol which I want to show a image however when i do click on button the page refreshes and does not show image?. I have a placeholder on aspx page and backend code i have this :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Control uc = Page.LoadControl("~/UserControls/Mycontrol.ascx");
placeholder1.Controls.Add(uc);
}
}
Do i need to do something in page_preinit or page_init ??
You should always reload the user control on the Page_init on each post back.
Dynamic controls added to the page must be added on every postback, not just the first one. Remove the !IsPostBack condition. Secondly, they have to be added during init or preinit, because that way, viewstate will be captured and restored properly (ASP.NET restores viewstate between init and load events).
Give the control an ID and also load the control in Page_init
uc.ID = "your id";

ASP.NET - Add Event Handler to LinkButton inside of Repeater in a RenderContent call

I've got a Sharepoint WebPart which loads a custom User Control. The user control contains a Repeater which in turn contains several LinkButtons.
In the RenderContent call in the Webpart I've got some code to add event handlers:
ArrayList nextPages = new ArrayList();
//populate nextPages ....
AfterPageRepeater.DataSource = nextPages;
AfterPageRepeater.DataBind();
foreach (Control oRepeaterControl in AfterPageRepeater.Controls)
{
if (oRepeaterControl is RepeaterItem)
{
if (oRepeaterControl.HasControls())
{
foreach (Control oControl in oRepeaterControl.Controls)
{
if (oControl is LinkButton)
{
((LinkButton)oControl).Click += new EventHandler(PageNavigateButton_Click);
}
}
}
}
}
The function PageNavigateButton_Click is never called however. I can see it being added as an event handler in the debugger however.
Any ideas? I'm stumped how to do this.
By the time RenderContent() is called, all the registered event handlers have been called by the framework. You need to add the event handlers in an earlier method, like OnLoad():
protected override void OnLoad(EventArge e)
{ base.OnLoad(e);
EnsureChildControls();
var linkButtons = from c in AfterPageRepeater.Controls
.OfType<RepeaterItem>()
where c.HasControls()
select c into ris
from lb in ris.OfType<LinkButton>()
select lb;
foreach(var linkButton in linkButtons)
{ linkButton.Click += PageNavigateButton_Click
}
}
Have you tried assigning the CommandName and CommandArgument properties to each button as you iterate through? The Repeater control supports the ItemCommand event, which is an event that will be raised when a control with the CommandName property is hit.
From there it is easy enough to process because the CommandName and CommandArgument values are passed into the event and are readily accessible.
You need to make sure that the link button is re-added to the control tree and/or that the event is rewired up to the control before the event fires.
Article # 4guysfromrolla
I've never done a SharePoint WebPart, so I don't know if this will apply. But if it were a plain-old apsx page, I'd say that by the time it's rendering, it's too late. Try adding the event handlers in the control's Init or PreInit events.
Edit: Wait, I think Dilli-O might be right. See the Adding Button Controls to a Repeater section at the end of http://www.ondotnet.com/pub/a/dotnet/2003/03/03/repeater.html. It's in VB.NET, but you can easily do the same thing in C#.
As others have pointed out, you're adding the event handler too late in the page life cycle. For SharePoint WebParts you'd typically want to override the class' OnInit/CreateChildControls methods to handle the activity.
YOu need your webpart to implement the INamingContainer marker interface, it is used by the framework to allow postbacks to return to the correct control...
Also the controls in your webpart all need to have an ID.

Categories