how can i use button click event and onclientclick together - c#

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','');";

Related

System.Web.UI.WebControls.Button click event not firing

In my C# code I have function to dynamically create buttons
private Button createPageButton(string id, string text, int navTo = 0)
{
Button btn = new Button();
btn.ID = id;
btn.Text = text;
btn.Click += new EventHandler(btnNavigate_To_Page);
return btn;
}
Which gets setup like this:
C#:
public void someMethod()
{
Button btnPage_First = createPageButton("btnFirst_Page", "First", 1);
panelNavPageButtons.Controls.Add(btnPage_First);
}
aspx:
<asp:Panel ID="panelPageNavButtons" CssClass="pageNavBtns" runat="server"></asp:Panel>
Problem: The btnNavigate_To_Page event does not fire. The createPageButton method is not called within Page_Load but if I include an asp button in the panel (see below) then any additional button I add on the server side works properly
<asp:Panel ID="panelPageNavButtons" CssClass="pageNavBtns" runat="server">
<asp:Button ID="btnPage_Prev" runat="server" OnClick="btnNavigate_To_Page" />
</asp:Panel>
I would like to set up all the buttons dynamically without including any reference to btnNavigate_To_Page in the .aspx file
You have to call someMethod method inside either Init or Load event.
The reason is dynamically created controls are not in the control tree, so you have to reload them on every post back with same id.
protected void Page_Init(object sender, EventArgs e)
{
someMethod();
}

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.

Adding a CheckChanged event handler to CheckBox inside a dynamically added UserControl

I have a UserControl that contains a CheckBox and a TextBox:
<asp:CheckBox runat="server" ID="chk1" />
<asp:TextBox runat="server" ID="tb1" />
On Page_Load I'm adding several of them dynamically them to a Panel on the page:
//loop through the results from DB
foreach (Thing t in Things)
{
//get the user control
MyUserControl c1 = (MyUserControl )Page.LoadControl("~/UserControls/MyUserControl.ascx");
//set IDs using public properties
c1.ID = "uc" + t.ID;
c1.CheckBoxID = "chk" + t.ID;
cl.TextBoxID = "tb" + t.ID;
//add it to the panel
myPanel.Controls.Add(c1);
//add the event handler to the checkbox
((CheckBox)myPanel.FindControl(c1.ID).FindControl(c1.CheckBoxID)).CheckedChanged += new EventHandler(CheckBox_CheckedChanged);
}
I then created the method for the event handler in the same page:
protected void CheckBox_CheckedChanged(object sender, EventArgs e)
{
string test = "breakpoint here";
}
When I put a breakpoint inside CheckBox_CheckedChanged it's never hit when the my checkbox gets clicked.
When I look at the view source, this is the code that gets generated:
<input id="ctl00_body_uc1_chk1" type="checkbox" name="ctl00$body$uc1$chk1" checked="checked" />
So, it doesn't seem to be picking up when I add the event handler. It's weird, cause it picks up everything else though.
Am I missing something?
Add the CheckBox.AutoPostBack property and set it to "true".
CheckBox cb = ((CheckBox)myPanel.FindControl(c1.ID).FindControl(c1.CheckBoxID));
if(cb != null)
{
cb.AutoPostBack = true;
}
"When I put a breakpoint inside CheckBox_CheckedChanged it's never hit when the my checkbox gets clicked."
If you want the event to fire when the check box gets clicked, you also need to set AutoPostBack = true on the check box. If you put the cursor in the text box and press return (causing a post back), does the event fire?

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