how to create an asp button dynamically and add event to it - asp.net

I'm trying to create a button dynamically on asp.net,but I can't add the event to it.What is wrong or missing below?
Thanks in advance
$
Button btn2 = new Button();
btn2.ID = "btnEdit";
btn2.Text = "Edit Member";
btn2.Click += new EventHandler(btnEdit_Click);
form1.Controls.Add(btn2);
I also tried like this:
$
Button btn2 = new Button();
btn2.ID = "btnEdit";
btn2.Text = "Edit Member";
btn2.Attributes.Add("OnClick","btnEdit_Click);
form1.Controls.Add(btn2);

read the article about the asp.net webforms life-cycle http://msdn.microsoft.com/en-us/library/ms178472.aspx. you have to create/recreate your controls everytime when loading the page (e.g. OnLoad-Method)
http://www.asp.net/web-forms/videos/aspnet-ajax/how-to-dynamically-add-controls-to-a-web-page

I think your trying to mix server side and client side events here.
The html attribute OnClick is a client side, when a user clicks on the button it fires a piece of JavaScript
The server event OnClick happens when a user clicks a button and it posts back to the server, which allows you to hook functions (server side) into that event.
Are you looking for server side or client side?
To add a client side event you can do
btn2.Attributes.Add("onclick","my_javascript_function");
To add a server side event you can do
btn2.Click += new System.EventHandler(this.MyMethod);
Where this.MyMethod is a method already seutp to handle the server side button click.

If I were right, you create buttons in Page_Load.
If it is check for postbacks.
if(!postback)
{
create your buttons.
}

Create a method for adding all Your dynamical controls as below
public void AddControls()
{
Button btn2 = new Button();
btn2.ID = "btnEdit";
btn2.Text = "Edit Member";
btn2.Click += new EventHandler(btnEdit_Click);
form1.Controls.Add(btn2);
}
and then call that method in Page_Load() Event & out side of the IsPostBack block as below
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
AddControls();
}
because for dynamically added control's view state will not load before Page_Load() evnt. go through this link for more info http://msdn.microsoft.com/en-us/library/vstudio/hbdfdyh7(v=vs.100).aspx

This should do the trick:
protected void Page_Load(object sender, EventArgs e)
{
Button b = new Button() { ID = "btnEdit", Text = "Edit Member" };
b.Click += (sd, ev) => {
// Do whatever you want to be done on click here.
Button me = (Button)sd; // This creates a self-reference to this button, so you can get info like button ID, caption... and use, like this:
me.Text = "Yay! You clicked me!";
};
form1.Controls.Add(b);
}

Related

How can I add a new dynamic control on button click?

When I click btnGDynamicCont I want to load the first set of controls, then on each further click of that button, add a new control (textbox) alongside the other ones, so each time it is clicked I am adding a new textbox across state.
Do you know where I should add the creation of the new textbox in order to keep it after each postback?
{
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["Generated"]) == "true")
GenerateDynamicControls();
}
public void GenerateDynamicControls()
{
TextBox txtDynamic = new TextBox();
txtDynamic.ID = "txtDynamic";
txtDynamic.Text = "Dynamic TextBox";
Page.Form.Controls.Add(txtDynamic);
TextBox txtDynamic2 = new TextBox();
txtDynamic2.ID = "txtDynamic2";
txtDynamic2.Text = "Dynamic Textbox";
Page.Form.Controls.Add(txtDynamic2);
}
protected void btnGDynamicCont_Click1(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["Generated"]) != "true")
{
GenerateDynamicControls();
ViewState["Generated"] = "true";
}
else
{
Response.Write("<h2>Controls are already exist in page</h2>");
}
}
}
}
Dynamic controls are usually recreated at the Page_Load method. For more information, please refer to the Dynamically Created Controls in ASP.NET article.
You can refer the below link where a very similar issue is addressed.
unable to add more than one server control dynamically in asp.net
Everytime a postback happens, you should recreate the already existing controls(dynamically added) in your page_load event and the new controls are to be created in the button_click event.
Use some logic to generate ids for the controls for the viewstate to be maintained. VIEWSTATE will be taken care automatically if the ids of the controls generated before and after postback are the same.
One way to keep track of the number of textboxes is to store the count in session.

Checkbox checked state change when visibility is set to false

I am having some trouble understanding the impact of setting checkbox visibility on the checked state at various stages in the page life cycle.
Given below is a sample code for a dynamically created checkbox.
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
check = new CheckBox();
check.AutoPostBack = true;
check.Text = "checkbox1";
check.ToolTip = "tooltip for checkbox1";
check.CheckedChanged += new EventHandler(check_CheckedChanged);
this.Form.Controls.Add(check);
Button btn = new Button();
btn.Text = "click me";
btn.Click += new EventHandler(btn_Click);
this.Form.Controls.Add(btn);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
check.Checked = true;
check.Text = "text reassigned.";
check.ToolTip = "tooltip reassigned";
}
}
protected override void OnPreRenderComplete(EventArgs e)
{
base.OnPreRenderComplete(e);
check.Visible = false;
}
The issue here is, when a postback occurs (I click on the button), then I notice in the Page_load event, the checkbox maintains the viewstate of the tooltip and text. However the checked state is changed to false and it fires a CheckedChanged event. Why is the behavior so?
Also, if I set the visibility of the checkbox in either PageLoad() or the OnPreRender() event, the checked state of the checkbox is maintained across postbacks and does not fire a CheckedChanged event.
I'm just curious as to what happens differently when the visibility is changed in the OnPreRenderComplete event so as to have the checkbox default to an unchecked state.
Well I have marked my last answer for deletion, as I didn't understand the question properly.
Well the things you are doing are:
You added the checkbox at runtime in Init event on server side.
Then in page load you set its value to true in the Not Post Back check.
Then you set its visibility to false in OnPreRenderComplete event
When you set the visibility to false on server side, the control is not generated on client side (you can check it by viewing the page source), as control is not created on client side so when you post back the page, the checkbox is created in page init and as it was not on client side so dot net doesn't know about its last value, so you get false for the check box.
If you need to check it more further, change your OnPreRenderComplete event as:
protected override void OnPreRenderComplete(EventArgs e)
{
base.OnPreRenderComplete(e);
//check.Visible = false;
check.Style.Add("display", "none");
}
By above line, the style is being added to the control, so the control is generated on client side but is not visible and you will get its value during the post back.

Event for Dynamically created Controls in ASP.Net

I've created an application in which I've created Dynamic Controls on Click Event of a Button. But the dynamically created Control Event will not Fire on Click of it.
Below is the Code I've written.
ImageButton closeImage = new ImageButton();
closeImage.ID = "ID"+ dr["ID"].ToString();
closeImage.AlternateText = "Delete";
closeImage.ImageUrl = "App_Themes/images/CloseButton.png";
closeImage.Attributes.Add("style", "float:right;cursor:pointer;margin: -19px 1px -10px;");
closeImage.EnableViewState = true;
closeImage.CommandName = "Delete";
closeImage.CommandArgument = dr["ID"].ToString();
closeImage.Attributes.Add("runat", "server");
closeImage.OnClientClick = "return confirm('Are you sure you want to remove this');";
closeImage.Click += new ImageClickEventHandler(this.closeImage_click);
protected void closeImage_click(object sender, ImageClickEventArgs e)
{
ImageButton ibDel = (ImageButton)sender;
}
The same code work if its placed on Page_Load(). Is there any other Solution to fire the event.
I would like to suggest that you read up on the following article on MSDN. It's about page lifecycle.The key part is to when controls are created. If the controls are created in the wrong stage, events will not be registered, and thus will not fire.
http://msdn.microsoft.com/en-us/library/ms178472%28v=vs.80%29.aspx

create a dynamic ModalPopupExtender from code behind does not work

I am trying to create a dynamic ModalPopupExtender from code behind that when i click on a button it pops a panel with a button in side.
i created a panel (named panel) with a button in side called ButtonOk (button.id ="ButtonOk")
but when i click the event handler of the first button (Button_Click) nothing happens please help me my code is:
protected void Button_Click(object sender, EventArgs e)
{
HiddenField hf = new HiddenField();
hf.ID = "hdnField";
AjaxControlToolkit.ModalPopupExtender modalPop = new AjaxControlToolkit.ModalPopupExtender();
modalPop.ID = "ModalPopupExtenderSelectFilds";
modalPop.PopupControlID =Convert.ToString(Page.FindControl(Convert.ToString(panel.ClientID))); //panel.ID;
modalPop.TargetControlID = Convert.ToString(Page.FindControl(Convert.ToString(hf.ClientID))); //"hdnField";
modalPop.OkControlID = "ButtonOk";
modalPop.BackgroundCssClass = "modalBackground";
modalPop.BehaviorID = "modalPopupExtenderSelectFilds";
modalPop.Show();
}
For help of other users, you will just have to add modalPop to area where control will be added to page
For example, this should be added at end of code
panel1.Controls.Add(modalPop);
check this code to add controls to panel:-
this.panel1.Controls.Add(modalPop);
In code behind, you can make this:
if (true)
{
var script = #"Sys.Application.add_load(function() { $find('behavoirIDModal').show(); });";
ScriptManager.RegisterStartupScript(this, GetType(), "ShowPopup", script, true);
}
edit this: behavoirIDModal

Creating ASP.NET Button dynamically using ajax call

I want to create a asp.net button control / link button control when user makes an ajax call to my server page (another asp.net page) and I wnt to do something on the button click event of this button. How to do this ? Do i need to use delegate ?
No, you don't need a delegate for this, it will be created for you. In your AJAX callback you should do something like this:
Button btn = new Button();
btn.Click += MyOnClickMethod; // must use +=, not =
btn.Text = "click me";
myUpdatePanel.Controls.Add(btn); // the AJAX UpdatePanel that you want to add it to
myUpdatePanel.Update(); // refresh the panel
The method MyOnClickMethod must have the same signature as a normal Click handler. Something like this will do:
protected void MyOnClickMethod(object sender, EventArgs e)
{
// do something
}
that's about it. There are many intricacies involved with dynamic controls, but the basis is as laid out above.

Resources