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.
Related
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);
I have problems with my dynamically link buttons in asp pages. I use them for making a custom paging for a grid view. The idea is that i want to display them 20 about 20. It is working for first 20. When i display them it's all right. Then i press next for displaying the next 20. When i press next, it displaying me, but if a press a button other than the initial 20, it is going me at the first 20.
My init page:
override protected void OnInit(EventArgs e)
{
base.OnInit(e);
if (this.Tag.Equals("Shareholder"))
{
InitComponents(false);
}
/// Must be done everytime the page loads.
InitializeList();
if (!IsPostBack)
InitializeUI();
}
Init link buttons
private void InitComponents(Boolean Prev)
{
PanelPager.Controls.Clear();
int nrInregistrari = Convert.ToInt32(DAActionar.CountActionari(11, LastBtnIndex));
if (Prev == true)
{
LinkButton lnkPrev = new LinkButton();
lnkPrev.Text = "Prev";
PanelPager.Controls.Add(lnkPrev);
}
int BtnDeAfisat = 0;
if (nrInregistrari > BTN_PER_SERIE * PAGE_SIZE)
{
BtnDeAfisat = BTN_PER_SERIE;
}
else
BtnDeAfisat = nrInregistrari / PAGE_SIZE + 1;
for (int index = 1; index <= BtnDeAfisat; index++)
{
int pageNo = index + LastBtnIndex;
LinkButton lnk = new LinkButton();
lnk.Click += new EventHandler(PageChange);
lnk.ID = "PageLink" + pageNo.ToString();
lnk.CommandName = "Page";
lnk.Text = " " + pageNo.ToString() + " ";
lnk.CommandArgument = index.ToString();
PanelPager.Controls.Add(lnk);
}
LinkButton lnkNext = new LinkButton();
lnkNext.Click += new EventHandler(NextPage);
lnkNext.Text = "Next";
PanelPager.Controls.Add(lnkNext);
LastBtnIndex += BtnDeAfisat;
}
event for next buttons
private void NextPage(object sender, EventArgs e)
{
InitComponents(true);
}
PageChange:
public void PageChange(object sender, EventArgs e)
{
int pageIndex = int.Parse((sender as LinkButton).CommandArgument) + 1;
object dataSource = GetDataSource(OwnerId, null, pageIndex);
PushData(dataSource);
}
In ASP.NET only the controls which are added as part of Page_Load will have their events attached and will be executed. Also in when a server side event is executed the page posts itself back and during that the page_load executes first and then the event handler code gets executed.
So your first set of button events executed coz they were attached to event as part of page_load. Now during event of those button you are calling InitComponents method. So as I explained during the event page_load happens first which calls InitComponents method, which adds button to panel but InitComponents method executes again as part of event handler code which removes controls from Panel and re-creates them and add them again to the Panel.
Now since controls created during 2nd execution of InitComponents method are not no part of page_load flow events attached to them are not firing when you click on them. It just posts back the page which executed InitComponents again and which creates new controls in the panel and they will have their events working fine because they are created as part of page_load flow.
Pardon me if it confuses you.
Now the solution to this would be to use a control which can create many buttons automatically for you based on the number of items and also fires events all the times.
I do not have anything working right now for you. I found this article with working sample code which you can consider as an example and implement in your work.
http://www.aspsnippets.com/Articles/Implement-Paging-in-DataList-control-in-ASPNet.aspx
The example explains how to display page numbers and also how to bind your data based on the selected page number.
I want to create a dynamic button when click a pop up appear and user key in then submit.
First of all I have dynamic button created depends on the table row
TableCell tc;
for (int i = 1; i < Approval_TBL.Rows.Count; i++)
{
TableRow tr = Approval_TBL.Rows[i];
tr.Cells.Add(tc = new TableCell());
Button tb = new Button();
tb.ID = Convert.ToString(i);
tb.Text = "Reject";
tb.CssClass = "btn btn-default";
tb.OnClientClick = "javascript:$find('popup1').show();return false;__doPostBack('btnReject_click','')";
tb.Click += new EventHandler(btnReject_click);
tc.Controls.Add(tb);
}
then I have the popup created using ajax:
<ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender1" runat="server"
TargetControlID="1"
BehaviorID="popup1"
PopupControlID="Panel1"
DropShadow="true"
CancelControlID="Button3"
OnOkScript="OkButtonClick"
BackgroundCssClass="BackgroundStyle" />
then I have created click event
protected void btnReject_click(object sender, EventArgs e)
{
//code
}
Currently looks like it only run Onclientclick event where the popup appear but it wont go in to btnReject_click. but if i remove the onclientclick, it will be able to go in the btnReject_click.
My way of doing is weird because i dont know how to use asp.net and most of my code i put it in server side (c#).
if you using jQuery then
$("selector").on('click',function(){
// your code here
});
Within your OnClientClick you return false;. Anything after that is not executed so the postback never happens. Remove the return and the postback should fire.
tb.OnClientClick = $find('popup1').show();__doPostBack('btnReject_click','');";
I am dynamically adding Link Buttons to my Gridview as seen below:
protected void addLinks()
{
foreach (GridViewRow gvr in gvData.Rows)
{
if (gvr.RowType == DataControlRowType.DataRow)
{
string itemNbr = gvr.Cells[1].Text;
LinkButton lb = new LinkButton();
lb.Text = itemNbr;
lb.Click += genericLinkButton_Click;
foreach (Control ctrl in gvr.Cells[1].Controls)
{
gvr.Cells[1].Controls.Remove(ctrl);
}
gvr.Cells[1].Controls.Add(lb);
}
}
}
This addLinks() function is called in my gridview_RowDataBound event and the Page Load event if(isPostPack).
The problem is that when I click the link buttons, the genericLinkButton_Click event does not get fired on my first click. It causes a postback, and then if I click it again, or click one of the other Link Buttons, the genericLinkButton_Click event is fired.
How can I make sure the click event happens on my first click?
Thanks!
My condolences for having to bother with WebForms.
When using Webforms and dynamically creating controls you are required to assign an ID to the created control before adding the control to the tree in order for them to work properly. Otherwise they will have changing ID's during the pagelifecycle resulting in the described behaviour.
private int _runningIndex = 0;
protected void gvData_RowCreated(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string itemNbr = e.Row.Cells[1].Text;
LinkButton lb = new LinkButton();
lb.ID = "btn" + (_runningIndex++).ToString();
lb.Text = itemNbr;
lb.Click += genericLinkButton_Click;
foreach (Control ctrl in e.Row.Cells[1].Controls)
{
e.Row.Cells[1].Controls.Remove(ctrl);
}
e.Row.Cells[1].Controls.Add(lb);
}
}
should be working.
RowDataBound is triggered only if the GridView gets databound, so when you call gvData.DataBind(). But dynamically created controls must be created again on every postback.
The most appropriate event to create controls dynamically in a GridView is RowCreated which is triggered on every postback. Note that you the GridViewRow's DataItem is null on postback. So you cannot access it's datasource as opposed to RowDataBound. But that seems not to be necessary anyway here.
Note also that you don't need to loop all rows in RowDataBound or RowCreated since these events are triggered for every row in the GridView anyway.
protected void gvData_RowCreated(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string itemNbr = e.Row.Cells[1].Text;
LinkButton lb = new LinkButton();
lb.Text = itemNbr;
lb.Click += genericLinkButton_Click;
foreach (Control ctrl in e.Row.Cells[1].Controls)
{
e.Row.Cells[1].Controls.Remove(ctrl);
}
e.Row.Cells[1].Controls.Add(lb);
}
}
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
}