Creating ASP.NET Button dynamically using ajax call - asp.net

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.

Related

Handling ServerClick event of a dynamic HtmlInputSubmit control

I am a beginner in ASP .Net programming.
I am developping a little training web application.
I have developped a web form where the user can add items into a cart.
The user's cart matches a session variable.
I check whether the user's cart is empty or not in the Page_PreRender event handler.
If the cart is not empty then a table is inserted into the form.
Each item in the cart matches a line in the table.
An item line contains an HtmlInputSubmit to remove the item from the cart.
Here is the code I have written to create dynamically the "Remove Item" HtmlInputSubmit :
submitSupprimerArt = new HtmlInputSubmit();
cellTblCaddie.Controls.Add(submitSupprimerArt);
submitSupprimerArt.Value = "Supprimer " + article.Id;
submitSupprimerArt.Attributes.Add("articleId", article.Id);
submitSupprimerArt.ServerClick += new EventHandler(submitSupprimerArt_Click);
When the user click the HtmlInputSubmit then a postback is made but the submitSupprimerArt_Click event handler is not called.
Can someone please give me a reason ?
I did not want to but I have finally looked at the solution of the training application.
I can describe operations needed to solve my problem but I can not explain precisely why the operations must be done.
The trick is to declare a PlaceHolder control in the ASPX page.
The PlaceHolder must be filled with "Remove Item" buttons from the Page_Load event handler as follows :
protected void Page_Load(object sender, EventArgs e)
{
// ...
caddie = (ListeArticles)this.Session["caddie"];
if (caddie != null)
{
foreach (Article article in caddie)
{
btnSupprimerArt = new Button();
this.phBoutonsSupprArt.Controls.Add(btnSupprimerArt);
btnSupprimerArt.ID = "btnSupprimerArt" + article.Id;
btnSupprimerArt.Command += new CommandEventHandler(btnSupprimerArt_Command);
btnSupprimerArt.CommandName = article.Id;
btnSupprimerArt.Text = "Supprimer " + article.Id;
}
}
}
The Controls property of the PlaceHolder is cleared from the Page_PreRender event handler.
Then the "Remove Item" buttons are created from the Page_PreRender event handler.
The "Remove Item" buttons are inserted this time into table cells.
Conclusion (Needs probably revision) :
Registering handlers to dynamic control events seems a little tricky.
Apparently every event handlers must be registered after the Page_Load event.

click event for HTML dynamic button

I'm developing a C# ASP.NET application under VS2010. I want to generate a dynamic table by writing HTML text into a literal, including dynamically inserted buttons on my table. I know how to create dynamic ASP.NET controls, but I have a small problem with dynamic HTML controls. I've created an HTML button but I don't know how to give it a server-side click function.
Can I create dynamic ASP.NET controls and insert them in my literal? How can I get a dynamically created button to trigger a server-side event?
I've used OnServerClick property for defining my server side function but it has no effect, how can I use this value?
If you want post back on your button click, you will have to add __doPostBack function on it's onclick event, for this you can add a button like
StringBuilder dynamicHtml = new StringBuilder();
dynamicHtml.Append("Your Html Code");
dynamicHtml.Append("<input type='button' id='btn1' name='btn1' onclick='__doPostBack(\'btn1\',\'\')' value='Click Here' />");
when you click on it, it will post back, and you can check Request.Form["__EVENTTARGET"] to find who post back the page.
By checking Request.Form["__EVENTTARGET"] in Page_Load event handler, you can call your any server side method like
protected void Page_Load(object sender, EventArgs e)
{
var eventTarget = Request.Form["__EVENTTARGET"].ToString();
if(eventTarget == "btn1")
{
CallMethod1();
}
}
private void CallMethod1()
{
//Code which you want to run
}

how to create an asp button dynamically and add event to it

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);
}

Row Editing in the grid doesn't work in first click

I have a user control which contains a grid and three buttons for add,edit and delete.
I have placed this user control on an asp.net page.
I have OnClick events for these buttons.
When i click on add and delete buttons it's working fine but when i click on edit button,the onclick event of edit button is fired but the row in the grid doesn't appear in the edit mode, i have to click two times.
I don't know where is the problem.The onclick event handler for edit button is as follows:
protected void btnEditBankAccount_Click(object sender, EventArgs e)
{
grdBankAccounts.EditIndex = grdBankAccounts.SelectedIndex;
grdBankAccounts.RowSelectingEnabled = false;
}
Anyone please help.
my user control has a method which binds the grid to the data source, it's as follows
public void SetSupplierData(SupplierType Supplier)
{
if (Supplier != null)
{
ViewState["SupplierID"] = Supplier.SupplierId;
grdBankAccounts.DataSource = Supplier.BankAccounts;
grdBankAccounts.DataBind();
Session["BankAccounts"] = Supplier.BankAccounts;
}
}
the SetSupplierData method is called from the page where i have my user control.
In order to get this "in-place editing" in grids to work, I typically have to data-bind twice:
once in the OnInit or OnLoad method so that the button click event handlers have the data available to work on
in the OnPreRender method again to show the new values / new state (editing or not)
Marc

handling events of controls added during runtime

I am adding controls dynamically during runtime using a conrolplace holder. i want to add buttons and handle their event. they will do the same thing but with different parameter. here is a sample of the code:
while (dataReader.Read())
{
Button edit = new Button();
PlaceHolderQuestions.Controls.Add(edit);
}
i need to handle the event of the buttons. Thanks
A couple of things:
Firstly you need to make sure the new Controls are added in the Page.OnInit event, so that they are added before the raised events are processed.
They also need to be added again on a postback!
They also need to have a unique ID set.
Finally you can handle the event just like you would in any C# app:
edit.Click += new EventHander(EditButton_Click);
and later in the code:
protected void EditButton_Click(object sender, EventArgs e)
{
// Do Something
}
You can just create a method, then add:
edit.Click += YourMethodName;
As long as the same button is created on postback before the eventhandler is raised, the event will fire.

Resources