Currently, I am doing a project for students' hostel and now I have to implement some search strategies about students.Here I have to create a button dynamically when the user clicks on the another server button in .aspx page and accordingly I have to create the onclick event handler for the newly created button. The code-snippet that I used is:
protected void btnsearchByName_Click(object sender, EventArgs e)
{
TextBox tbsearchByName = new TextBox();
Button btnsearchName = new Button();
tbsearchByName.Width = 250;
tbsearchByName.ID = "tbsearchByName";
tbsearchByName.Text = "Enter the full name of a student";
btnsearchName.ID = "btnsearchName";
btnsearchName.Text = "Search";
btnsearchName.Click += new EventHandler(this.btnsearchName_Click);
pnlsearchStudents.Controls.Add(tbsearchByName);
pnlsearchStudents.Controls.Add(btnsearchName);
}
protected void btnsearchName_Click(object sender, EventArgs e)
{
lblsearch.Text = "btnsearchName_Click event fired in " + DateTime.Now.ToString();
}
Here, the problem is newly created eventHandler doesnot get fired. I have gone through this site and looked several questions and answers and also gone through the page life-cycle and they all say that the dynamic button should be on Init or Pre_init, but my problem is I have to create it when another button is clicked, how can it be possible?
You need to add the click handler for the button on every postback.
you could look for the button in the search students panel on page load or try the page OnInit() method to add the handler when its created.
Also check here:
Dynamically added ASP.NET button click handler being ignored
and here:
asp.net dynamically button with event handler
and here:
asp:Button Click event not being fired
(all of which give similar suggestions)
Try this http://msdn.microsoft.com/ru-ru/library/system.web.ui.webcontrols.button.command(v=vs.90).aspx
btnsearchName.Command += new CommandEventHandler(this.btnsearchName_Click);
btnsearchName.CommandName = "Click";
You need to recreate the button and attach the event handler every time. For this, create a list of button and save it on session. On page load, go through the List and create the button every time
public Button create_button()
{
btnsearchName.ID = "btnsearchName";
btnsearchName.Text = "Search";
btnsearchName.Click += new EventHandler(this.btnsearchName_Click);
return btnsearchName;
}
public TextBox create_textbox()
{
TextBox tbsearchByName = new TextBox();
Button btnsearchName = new Button();
tbsearchByName.Width = 250;
tbsearchByName.ID = "tbsearchByName";
tbsearchByName.Text = "Enter the full name of a student";
return tbsearchByName;
}
protected void btnsearchByName_Click(object sender, EventArgs e)
{
TextBox tbsearchByName = create_textbox();
Button btnsearchName = create_button();
//add to panels
pnlsearchStudents.Controls.Add(tbsearchByName);
pnlsearchStudents.Controls.Add(btnsearchName);
//add to session
List<Button> lstbutton = Session["btn"] as List<Button>
lstbutton.add(btnsearchName);
//similarly add textbox
//again add to session
Session["btn"] = lstbutton
}
public override page_load(object sender, eventargs e)
{
//fetch from session, the lstButton and TextBox and recreate them
List<Button> lstbutton = Session["btn"] as List<Button>;
foreach(Button b in lstbutton)
pnlsearchStudents.Controls.Add(b);
//similar for textbox
}
I am not sure but may be you have to override the OnInit() method like this.
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
}
You just need to add this code on ready state of jquery code and it will work fine for the dynamic button too
$(document).ready(function(){
$('input#tbsearchByName').click(function(){
// code goes here
});
});
Related
I'm attempting to create a "server control" that derives from WebControl. This needs to be done entirely in C# so that it can be compiled into a .dll. I am not interested in creating a user control with a .ascx file (I actually already have a "user control" but I want to add it to a library so I'm converting it).
My control is dead simple right now and I can't get a button event to fire:
public class ButtonWrapper : WebControl
{
protected Button button;
public event EventHandler<Events.GenericEventArgs<Tuple<int, string>>> ButtonClicked;
public void Button_Click(object o, EventArgs e)
{
ButtonClicked(this, new Tuple<int,string)(0, "abc"));
}
public void WHERE_DO_I_PUT_THIS_CODE()
{
button = new Button()
{
ID = "button",
Text = "Button"
};
button.Click += new EventHandler(Button_Click);
}
}
Where do I need to "create" the button? I currently have it in an overloaded CreateChildControls():
protected override void CreateChildControls()
{
this.Controls.Clear();
button = new Button()
{
ID = "button",
Text = "Button"
};
button.Click += new EventHandler(Button_Click);
this.Controls.Add(button);
this.ChildControlsCreated = true;
}
The control loads just fine, but when I click on the button, the page just refreshes and the event is never fired. I want to the button in ButtonWrapper to fire so that the parent page can listen. I think I'm close but I'm missing something simple.
Edit: I don't quite have the right event variables types for EventArgs passing and such when I was simplifying the problem for this question.
I created new solution and i tried it.
You can download from this link : http://dosya.co/download.php?id=51BACA121
I m at work and most of upload sites blocked. So i couldnt upload another site. If u cant download i can try find different upload site.
This question already has an answer here:
Event won't fire to dynamically added control
(1 answer)
Closed 2 years ago.
I saw lots of thing about this topic but i can't fin a solution.
I add many dropdown list with one event but they are not firing SelectedIndexChanged evet.
Here is drplist creator code:
foreach (var row in cmdSelectCats.ExecuteReader())
{
var id = row["ProductCategoryID"].ToString();
var dropDownStatus = new DropDownList {ID = "DrpStatus-" + id};
dropDownStatus.Items.Add(new ListItem("Aktif", "1"));
dropDownStatus.Items.Add(new ListItem("Pasif", "2"));
dropDownStatus.AutoPostBack = true;
dropDownStatus.SelectedIndexChanged += Status_SelectedIndexChanged;
var tableCell = new TableCell();
tableCell.Controls.Add(dropDownStatus);
dropDownStatus.SelectedValue = row["ProductCategoryStatusID"].ToString();
tableRow.Cells.Add(tableCell);
TblCatList.Rows.Add(tableRow);
}
And ofcourse my Event:
public void Status_SelectedIndexChanged(object sender, EventArgs e)
{
//DO SOMETHING
}
What am i missing?
This is a common issue and it's related to the page life cycle:
Take a look at the following questions:
Click events on Array of buttons
Button array disappears after click event
Dynamically create an ImageButton
Now the basic steps to remember when creating dynamic controls are:
Dynamic controls should be created in the PreInit event when you are not working with a master page, if you are, then create the controls in the Init event
Avoid setting properties that can be changed in each post in these events because when the view state is applied (in a post event) the properties will be overridden
Dynamic controls must be created every time the page is posted, avoid this if(!this.IsPostBack) this.CreatemyDynamicControls();
When you create the controls in the PreInit or Init events, their states will be automatically set in a post event, which means in the LoadComplete event your controls will contain their state back even when you create them again in each post and even when you did not explicitly set their state. Note this behavior is different when you are dealing with controls created at design time, in that case, the event where the state has been set is the Load event
Event subscription should occur before the PageLoadComplete or they will not be raised
Consider the following description from MSDN
If controls are created dynamically at run time or declaratively within templates of data-bound controls, their events are initially not synchronized with those of other controls on the page. For example, for a control that is added at run time, the Init and Load events might occur much later in the page life cycle than the same events for controls created declaratively. Therefore, from the time that they are instantiated, dynamically added controls and controls in templates raise their events one after the other until they have caught up to the event during which it was added to the Controls collection.
The above is not so clear to me, but I have found the following. The following TextBox's are created at design time
protected void Page_PreInit(object sender, EventArgs e)
{
this.txtDesignTextBox1.Text = "From PreInit";
this.txtDesignTextBox1.Text += DateTime.Now.ToString();
}
protected void Page_Init(object sender, EventArgs e)
{
this.txtDesignTextBox2.Text = "From Init";
this.txtDesignTextBox2.Text += DateTime.Now.ToString();
}
protected void Page_Load(object sender, EventArgs e)
{
this.txtDesignTextBox3.Text = "From Load";
this.txtDesignTextBox3.Text += DateTime.Now.ToString();
}
At first sight you might think that in every post all the textboxes are updated with the current date, but this is not the case, since they were created at design time they follow strictly the ASP.Net page life-cycle which means, their state is overriden after the PreInit and Init events, only the txtDesignTextBox3 is updated in every post because its Text property is updated after the view state has been set (in the Load event).
But with dynamic controls the behavior is different, remember the MSDN description:
for a control that is added at run time, the Init and Load events might occur much later in the page life cycle
Consider the following:
protected void Page_PreInit(object sender, EventArgs e)
{
var textBox = new TextBox { Text = "From PreInit", Width = new Unit("100%") };
textBox.Text += DateTime.Now.ToString();
this.myPlaceHolder.Controls.Add(textBox);
}
protected void Page_Init(object sender, EventArgs e)
{
var textBox = new TextBox { Text = "From Init", Width = new Unit("100%") };
textBox.Text += DateTime.Now.ToString();
this.myPlaceHolder.Controls.Add(textBox);
}
protected void Page_Load(object sender, EventArgs e)
{
var textBox = new TextBox { Text = "From Load", Width = new Unit("100%") };
textBox.Text += DateTime.Now.ToString();
this.myPlaceHolder.Controls.Add(textBox);
}
In this case, the controls behave slightly different, in this case, in each post, the controls are never updated not even the controls created in the Load event
The reason is their life-cycle events occurs much later in the page-life cycle which means their state is overridden even after the Load event
To solve this, you can use the LoadComplete event, in this event you can change the state of dynamic controls:
protected void Page_LoadComplete(object sender, EventArgs e)
{
var textBox = new TextBox { Text = "From LoadComplete", Width = new Unit("100%") };
textBox.Text += DateTime.Now.ToString();
this.myPlaceHolder.Controls.Add(textBox);
}
In this case, the state will be updated in each post.
However, take in consideration that you should subscribe to dynamic controls events, before the LoadComplete event or they will not be raised.
... I know I hate this kind of behavior, that's why I love MVC
As a quick reference for controls created at design time: Notice how the LoadViewState method is called after the PreInit and Init events but before the Load event. The Load event is considered stable because in this event you can access the view state of your controls. Also notice that the RaisePostBackEvent method represent the control event that caused the post back, this can be, the SelectedIndexChanged, Click, etc this event is handled after the Load event
For a complete detailed specification read the MSDN Page Life-Cycle documentation
I have usually seen this caused by a page lifecycle problem. If the control is only created when an event is fired, then when your index changed event fires the control doesn't exist to bind it to on the postback.
Example:
MyEvent fires. Drop-down created. Event Handler specified.
Index Changed event triggered. Page reloads. Drop-down not found, cannot fire.
You have to ensure the drop-down is created before .NET attemps to handle the event.
You are missing:
1- Override SaveViewState
2- Override LoadViewState
I provide a sample code for this question. I test it. It's work.
ASPX:
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<div id="myDiv" runat="server">
</div>
<asp:Label ID="lblDescription" runat="server"></asp:Label>
</form>
Code Behind:
public partial class Default : System.Web.UI.Page
{
private List<string> values = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
}
protected override object SaveViewState()
{
object baseState = base.SaveViewState();
object[] allStates = new object[2];
allStates[0] = baseState;
allStates[1] = values;
return allStates;
}
protected override void LoadViewState(object savedState)
{
object[] myState = (object[])savedState;
if (myState[0] != null)
base.LoadViewState(myState[0]);
if (myState[1] != null)
{
values = (List<string>)myState[1];
MyRender();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
DropDownList ddl = new DropDownList();
ddl.ID = "ClientID" + i;
ddl.Items.Add("Item 1");
ddl.Items.Add("Item 2");
ddl.AutoPostBack = true;
values.Add(ddl.SelectedValue);
myDiv.Controls.Add(ddl);
}
}
private void MyRender()
{
for (int i = 0; i < values.Count; i++)
{
DropDownList ddl = new DropDownList();
ddl.ID = "ClientID" + i;
ddl.Items.Add("Item 1");
ddl.Items.Add("Item 2");
ddl.AutoPostBack = true;
ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
myDiv.Controls.Add(ddl);
}
}
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
lblDescription.Text = ((DropDownList)sender).ID + ": Selected Index Changed";
}
}
I need to generate a dynamic list of buttons, I already did, with an event handler attached to it.
However the event handler is not being executed.
private void GetOptions(EcoBonusRequest request)
{
var ecobonuswworkflow = WorkflowFactory.CreateEcobonusWorkflow();
ecobonuswworkflow.SetCurrentStep(request.CurrentStatus);
var currentoptions = ecobonuswworkflow.GetCurrentOptions();
foreach(var option in currentoptions)
{
var btn = new Button() {Text = option.OptionName};
btn.Click +=new EventHandler(btn_Click);
Buttons.Controls.Add(btn);
}
}
void btn_Click(object sender, EventArgs e)
{
var btn = (Button) sender;
string command = btn.Text;
EcoBonusRequest request = this.GetDBRequest(RequestBaseId.Value);
EcoBonusRequestBL.AddWorkflowHistoryItem(request, command,CurrentUser, command);
}
The controls that you add dynamically in your page must be added in Page_init event, and they must have unique Ids. If you are adding textboxes or some other controls where user can input or change value, than on every post back when these controls are re-added they must have same IDs.
I want to create a method in code behind that creates a button and places it in a PlaceHolder. I want this button to have a Click event.
After calling the "test" method button is placed correctly but the click event is not called.
private void test()
{
Button linkBtn1 = new Button();
linkBtn1.Text = "linkBtn1";
linkBtn1.OnClientClick = "return false;";
linkBtn1.Click += new EventHandler(linkBtn1_Click);
PagesPlaceHolder.Controls.Add(linkBtn1);
}
void linkBtn1_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
Removing the OnClientClick = "return false;" is necessary but not sufficient to get this to work. If you want the event handler on the dynamically added button to be triggered, you'll need to add this button every time the page loads.
One simple way would be to save the fact that the button has been added in ViewState, and then check that on PageLoad, and re-add the button if needed.
Here's a sample that works for me (and throws the exception when clicked)
protected void Page_Load(object sender, EventArgs e)
{
//if the button was added previously, add it again
if (ViewState["Added"] != null && (bool)ViewState["Added"])
addButton();
}
//this is the method that adds the button
protected void add_Click(object sender, EventArgs e) {
ViewState["Added"] = true;
addButton();
}
private void addButton() {
Button linkBtn1 = new Button();
linkBtn1.Text = "linkBtn1";
linkBtn1.Click += new EventHandler(linkBtn1_Click);
placeholder1.Controls.Add(linkBtn1);
}
void linkBtn1_Click(object sender, EventArgs e) {
throw new Exception("Button Click Event Triggered. Hello yellow screen!!!");
}
As #oleksii points out, have the clientside code is returning false so the form never gets submitted. You need to comment this out, then your event handler should fire.
I am creating 7 buttons on the fly
when i create the buttons i am trying to have an event handler than can deal with all clicks in one method via a switch. Ideally i want to pass an id with the button that indicates what was clicked, opposed to this solution of
void pdfButton_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
Console.WriteLine(b.Text);
}
as all of the buttons using this event handler have the same text. I have a unique id associated witht the buttons but no idea how to send them
thanks
You can use the Name or Tag properties.
Put the ID in the Tag property on the button when you create them and then check the ID in your event handler.
Button button = new Button();
button.Tag = 1;
...
void pdfButton_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
switch ((int)b.Tag)
{
...
}
}
First: Bad practice to handle several clicks in one event via switch. But however a solution would be:
Create your own control which inherits the button and ad your ID as an property. So you can access it via:
MyButton b = (MyButton)sender;
switch(b.ID) {
//Code goes here
}
If each button you add has a unique Id, why not just use the ID property of the button?
Button button = new Button();
button.ID= "Button1";
//...
void pdfButton_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
switch(button.ID)
{
case "Button1":
//...
}
}