LinkButton Click event not firing after programatic hookup - c#

I am creating linkbuttons inside of a panel and hooking up an event handler to the Click event. It isn't firing. This is my code. Is this lost on postback?
foreach (var item in clients)
{
var codeLb = new LinkButton() { Text = item.CLIENT_CODE, CssClass = "codeColumn", CommandArgument = item.CLIENT_CODE, CommandName = "Select" };
codeLb.Click += ResultsLinkButton_Click;
ResultsPanel.Controls.Add(codeLb);
var nameLb = new LinkButton() { Text = item.CLIENT_NAME, CssClass = "nameColumn", CommandArgument = item.CLIENT_CODE, CommandName = "Select" };
nameLb.Click += ResultsLinkButton_Click;
ResultsPanel.Controls.Add(nameLb);
}

Yes every dynamically created controls are lost on after postback.
You need to recreate them again on postback and again hook up the Event Handler.
You can read more
https://web.archive.org/web/20210330142645/http://www.4guysfromrolla.com/articles/092904-1.aspx
Dynamic Controls and Postback
Hope it helps.

Related

C# Dynamic RadioButton in Update Panel is not firing on first click?

I have a number of radio buttons created dynamically inside a loop and added to a div inside update panel. On each postback request triggered by checked change event, I recreate the radio buttons in my page_init method. My problem is the radio button I selected is not checked and the checked changed event is not firing on first click. But on subsequent clicks, it works normally and the checked changed event is fired. Only the first click is not firing. What could be the issue?
Simple dynamic radio button.
RadioButton btn2 = new RadioButton();
btn2.Text = "TEST";
btn2.CheckedChanged += Btn2_CheckedChanged; ;
btn2.AutoPostBack = true;
pricetbldiv.Controls.Add(btn2);
private void Btn2_CheckedChanged(object sender, EventArgs e)
{
RadioButton btn = (RadioButton)sender;
string text = btn.Text;
}
Try to assign group and ID
btn2.ID = "Text";
btn2.Text = "Text";
btn2.GroupName = "RB";
btn2.CheckedChanged += new EventHandler(Btn2_CheckedChanged);

Dynamically created image button click event is not fired

On dynamically created table based on some condition i've added imagebutton dynamically. parallelly i want to add event for this image button click but the click event is not getting fired. here is my code snippet.
private void createTable()
{
TableRow tableRow = new TableRow();
TableCell ImageCell = new TableCell();
ImageButton imgBtndeleteAttr = new ImageButton();
imgBtndeleteAttr.ID = "imgbtn_" + i.ToString() + j.ToString();
imgBtndeleteAttr.CssClass = "deleteDynamic";
imgBtndeleteAttr.OnClientClick = "javascript:return confirm('Do you want to delete this Attribute?');";
imgBtndeleteAttr.Click += new System.Web.UI.ImageClickEventHandler(imgBtndeleteAttr_Click);
ImageCell.Controls.Add(imgBtndeleteAttr);
tableRow.Cells.Add(ImageCell);
}
and here is the event
protected void imgBtndeleteAttr_Click(object sender, ImageClickEventArgs e)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "lnk",
"<script type = 'text/javascript'>alert('Image button Clicked');</script>");
}
Its a bad idea to use dynamic controls in asp. The controls have to be recreated on postback. So if you create a button dynamically and click it, postback happens and event is triggered but due to postback the button which triggered the event is destroyed and the raised event is discarded.

Adding Triggers dynamically on UpdatePanel for dynamially added controls

I am Adding array Buttons to a simple panel dynamically which is located in an Update Panel, now I want to Add triggers for UpdatePanel on click event of these buttons. My codes is as below:
protected void AddButtons()
{
Button[] btn = new Button[a];
for (int q = 0; q < a; q++)
{
btn[q] = new Button();
buttonsPanel.Controls.Add(btn[q]);
btn[q].ID = "QID" + q;
btn[q].Click += new EventHandler(_Default_Click);
btn[q].Attributes.Add("OnClick", "Click(this)");
AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();
trigger.ControlID = btn[q].ID;
trigger.EventName = "Click";
UpdatePanel2.Triggers.Add(trigger);
}
}
Now click event is not fired when i click on any of these bottons and buttons are getting removed.
Please note that these buttons are not available on Page_Init() method.
You need to assign UniqueID instead of ID to AsyncPostBackTrigger.ControlID property. Try to use the following code:
AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();
trigger.ControlID = btn[q].UniqueID;
trigger.EventName = "Click";
UpdatePanel2.Triggers.Add(trigger);
I came across this post when I was attempting to dynamically add triggers to an update panel which contained a gridview. I have buttons in the gridview and defining the trigger in the page doesn't work as a unique ID for each button is generated when each row is created.
Generating the trigger like such;
AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();
trigger.ControlID = btn[q].UniqueID;
trigger.EventName = "Click";
UpdatePanel2.Triggers.Add(trigger);
did not work for me. The control could not be found, however when using the RegisterPostbackControl or the RegisterAysncPostbackControl commands it worked.
The end example is as follows;
protected void BankAccountDocumentGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton linkButton = (LinkButton)e.Row.Cells[3].FindControl("DocumentsDownloadButton");
ScriptManager.GetCurrent(Page).RegisterPostBackControl(linkButton);
}
}
I figured that the original poster or others who come across this post may benefit from my findings.

Datagrid EditItemTemplate button event not firing

I am dynamically creating an Item template in a Gridview.
TemplateColumn BtnTmpField = new TemplateColumn();
BtnTmpField.ItemTemplate = new DynamicallyTemplatedGridViewHandler(ListItemType.Item, "Edit", "Button");
BtnTmpField.HeaderTemplate = new DynamicallyTemplatedGridViewHandler(ListItemType.Header, "Edit", "Command");
BtnTmpField.EditItemTemplate = new DynamicallyTemplatedGridViewHandler(ListItemType.EditItem, "Update", "Button"); dgdefault.Columns.Add(BtnTmpField);
public void InstantiateIn(System.Web.UI.Control Container)
{
switch (ItemType)
{
case ListItemType.Header: Literal header_ltrl = new Literal();
header_ltrl.Text = "" + FieldName + "";
Container.Controls.Add(header_ltrl);
break;
case ListItemType.Item:
switch (InfoType)
{
case "Button":
LinkButton edit_button = new LinkButton();
edit_button.ID = "edit_button";
edit_button.Text = "Edit";
edit_button.CommandName = "Edit";
Container.Controls.Add(edit_button);
break;
}
break;
case ListItemType.EditItem:
if (InfoType == "Button")
{
LinkButton update_button = new LinkButton();
update_button.ID = "update_button";
update_button.CommandName = "Update";
update_button.Text = "Update ";
LinkButton cancel_button = new LinkButton();
cancel_button.ID = "cancel_button";
cancel_button.CommandName = "Cancel";
cancel_button.Text = "Cancel";
Container.Controls.Add(update_button);
Container.Controls.Add(cancel_button);
}
break;
}
}
When I select the "Edit" button the "Update" and "Cancel" buttons show up with the selected row editable. The ItemCommand event of the DataGrid fires correctly when "Edit" is clicked. When I click the "Update" or "Cancel" buttons nothing fires. The ItemCommand doesn't fire, and neither does the UpdateCommand or CancelCommand when I explicitly put the onUpdateCommand or onCancelCommand in the ascx page. I can't figure out why nothing is firing when the buttons in the EditItemTemplate is clicked. Also Everything is being loaded on every page_init postback. Any tips would be helpful
I figured it out. I basically created an item template, and added 3 separate buttons without using the edititem. In the data grid itemdatabound function, I just hide and show the buttons that need to be shown.
Are you rebinding the events in the grid's PreRender?
I had the same issue today. I noticed that it was calling the "Header" template for edit items. not sure why, but add the following just before "switch":
System.Diagnostics.Debug.WriteLine(string.Format("Template: {0}",ItemType.ToString()));
if you're testing with a small-ish number of records, you should be able to see that it calls the "header" item type when you attempt to edit the record.
I'd be curious to know if you're experiencing the same thing.

asp.net - Button event does not fire up

I have a search button on my page that runs a query on a DB, pulls out and displays some entries in a table, and for each entry I create a button. It looks something like this:
List<Friend> friends = SearchFriend(searchStr);
foreach (Friend f in friends)
{
TableCell addCell = new TableCell(), nameCell = new TableCell();
addCell.Text = "";
if (!f.IsMyFriend)
{
LinkButton addFriendBtn = new LinkButton();
addFriendBtn.Text = "Add as Friend";
addFriendBtn.Click += new EventHandler(addFriendBtn_Click);
addFriendBtn.ID = "add_" + f.ID.ToString();
addCell.Controls.Add(addFriendBtn);
}
nameCell.Text = f.Name;
TableRow row = new TableRow();
row.Cells.Add(addCell);
row.Cells.Add(nameCell);
SearchFriendTable.Rows.Add(row);
}
Problem is that the LinkButton event does not fire when it is pressed (changing LinkButton to a simple Button does not fix this either).
This is the html that I get in this portion:
<td><a id="ctl00_contentPH_add_2" href="javascript:__doPostBack('ctl00$contentPH$add_2','')">Add as Friend</a></td>
Also - when I put a breakpoint on Page_Load I do see the __EVENTTARGET with this control's id in it - however the event never starts running.
Any clues?
Thanks.
Adding to Himadri's answer:
Dynamically added controls need to be rewired in page init. Then the event will fire. I had a very similar issue Dynamically loaded Controls in a wizard
Where and when did you created that button?
If you dynamically create Buttons and want to listen to a event you have to create that button in the PageInit event. Always! So do not use if(!IsPostback)
Try with this.
<td><a id="ctl00_contentPH_add_2" href="javascript:__doPostBack('<%=ct100_contentPH_add_2.ClientId %>','')">Add as Friend</a></td>
Add event handler for the link buttons and handle those events.
if (!f.IsMyFriend)
{
LinkButton addFriendBtn = new LinkButton();
addFriendBtn.Text = "Add as Friend";
addFriendBtn.Click += new EventHandler(addFriendBtn_Click);
addFriendBtn.ID = "add_" + f.ID.ToString();
addFriendBtn.Click += new EventHandler(addFriendBtn_Click);
addCell.Controls.Add(addFriendBtn);
}
the event:
protected void addFriendBtn_Click(object sender, EventArgs e)
{
LinkButton lnk = (LinkButton)sender;
// do your coding
}

Categories