Why is my button's click event not firing? - c#

I have two Buttons on my Sharepoint 2010 Web Page. One fires (server-side), the other doesn't*. They are set up similarly. Here is the one that does fire:
Button btnSave = new Button();
btnSave.Text = "Save";
btnSave.Click += new EventHandler(btnSave_Click);
this.Controls.Add(btnSave);
. . .
private void btnSave_Click(object sender, EventArgs e)
{
LiteralControl message = null; // this breakpoint is hit, sho' nuff
. . . // code elided for brevity
}
...and here is the one that isn't invoked:
Button btnGeneratePDF = null;
. . .
btnGeneratePDF = new Button();
btnGeneratePDF.Text = "Generate PDF";
btnGeneratePDF.UseSubmitBehavior = true; // trying this after it didn't work without it... (still doesn't work)
btnGeneratePDF.Click += new EventHandler(btnGenPDF_Click);
this.Controls.Add(btnGeneratePDF);
private void btnGenPDF_Click(object sender, EventArgs e)
{
GeneratePDF(listOfListItems); // breakpoint here never reached
}
Why is btnSave's handler invoked when I click it, but btnGeneratePDF's handler is not?
I can get buttons to fire client-side (jQuery) by using HtmlButtons, but I need this one to fire server-side/C#.
UPDATE
Would the fact that I'm creating the pdfgen button inside the click handler of the other Button have anything to do with this? Here's the significant part of that:
private void btnSave_Click(object sender, EventArgs e)
{
try
{
. . . relatively insignificant code elided for brevity
Button btnGeneratePDF = new Button();
btnGeneratePDF.Text = "Generate PDF";
btnGeneratePDF.UseSubmitBehavior = true; // trying this after it didn't
work without it...still doesn't work; don't know why - configuration of this
button is the same as for btnSave
btnGeneratePDF.Click += new EventHandler(btnGenPDF_Click);
this.Controls.Add(btnGeneratePDF);
. . . relatively insignificant code elided for brevity
?
UPDATE 2
Only the first (btnSave) button (and not the identically-created btnGeneratePDF button) is marked as type="submit":
<input type="submit" name="ctl00$ctl24$g_5f3fedca_19f7_4bc3_b84e_efbef0c48a33$ctl00$ctl152" value="Save" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$ctl24$g_5f3fedca_19f7_4bc3_b84e_efbef0c48a33$ctl00$ctl152", "", true, "", "", false, false))" />
I believe only one button of type submit is allowed, but I tried to shove btnSave out of the way when I was done with it by setting its Enabled property to false, but that did nothing (good).

You must recreate the dynamic control in page processing. Here is an example of how to do it:
protected void Page_Load(object sender, EventArgs e)
{
Button b = new Button();
b.ID = "one";
b.Text = "one";
b.Click += B_Click;
this.form1.Controls.Add(b);
// this is where the dynamic control is created if id is in postback
if (Request["two"] != null)
{
Button x = new Button();
x.ID = "two";
x.Text = "two";
x.Click += X_Click;
this.form1.Controls.Add(x);
}
}
private void B_Click(object sender, EventArgs e)
{
Button x = new Button();
x.ID = "two";
x.Text = "two";
x.Click += X_Click;
this.form1.Controls.Add(x);
LabelOutput.Text += " ...one";
}
private void X_Click(object sender, EventArgs e)
{
LabelOutput.Text += " ...two";
}

If you assign the click event handler of the "pdf" button inside the click event of the Save button means that the PDF button is dynamically created and its click event assigned each time you press click on the save button. Only at that time the pdf will get its event assigned.

This is how I got it to work:
0) Declare button at the top:
Button btnGeneratePDF = null;
1) Create and configure it within the Page_Load() event (as suggested by Michael Palermo)
btnGeneratePDF = new Button();
btnGeneratePDF.Text = "Generate PDF";
btnGeneratePDF.UseSubmitBehavior = true; // I don't know if this is necessary
btnGeneratePDF.Click += new EventHandler(btnGenPDF_Click);
btnGeneratePDF.Visible = false;
this.Controls.Add(btnGeneratePDF);
Note that visible is set to false at first
2) Make the "Generate PDF" button visible within the "btnSave" click handler:
btnGeneratePDF.Visible = true;
That's it - it works fine now.

Related

Troubles with dynamic c# asp.net controls update

I'm currently working on a website using c# and asp.net. For this purpose, I need to create dynamic controls but I enconter some issues. I already read official documentation and searched for lots of tutorial but unfortunately, no one allowed me to fix this problem.
Here is a very simplified example of what I'm trying to do;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
CreateControls();
else
UpdatePage();
}
protected void CreateControls()
{
Button button1 = new Button();
button1.ID = "_Button1";
button1.Text = "Button1";
button1.Click += new System.EventHandler(_ClickEvent);
_Panel.Controls.Add(button1);
Button button2 = new Button();
button2.ID = "_Button2";
button2.Text = "Button2";
button2.Click += new System.EventHandler(_ClickEvent);
_Panel.Controls.Add(button2);
}
protected void UpdatePage()
{
Button button1 = ((Button)_Panel.FindControl("_Button1"));
button1.Text = "I went through UpdatePage and changed";
Button button2 = ((Button)_Panel.FindControl("_Button2"));
button1.Text = "I went through UpdatePage and changed";
}
protected void _ClickEvent(object sender, EventArgs e)
{
}
The aim here would just be to change the buttons' text when clicking on one of them. "Page_Load" method is correctly called as well as the "UpdatePage" one, but in the latter, Button1 and Button2 controls have disappeared (they are not in the panel controls anymore) and an NullPointer exception is obviously raised.
Would anybody have an explanation ? I know I probably missed something about page life cycle but could not find any clear solution anywhere.
Thanks a lot !
You are creating the controls the first time the page is loaded, but the Page_Load event is too late to add controls to the page and have WebForms know about that.
On the initial page load, somewhere between the OnInit and Page_Load, WebForms makes a note of what controls are currently on the page and sets them up in the view state and all of that stuff, so that they next time you post back it knows those controls should be there. If you don't add your controls until Page_Load, WebForms isn't really paying attention any more to what you're adding to the page, so they next time you post back it doesn't know to put those controls on the page.
Move your CreateControls call into the OnInit method. This will tell WebForms at the appropriate time to create the controls (about the same time that any controls from the .aspx markup get added, although slightly later). Then WebForms will be aware of those controls and will apply any view state necessary (if it's a postback), and then finally on Page_Load you can muck with the control data with your UpdatePage call.
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
CreateControls();
}
Think of OnInit as "put all of the controls on the page and wire up event handlers".
Think of Page_Load as "put data into the controls that are already there".
The controls that you are creating dynamically will be lost on postback. Try this:
protected void Page_Load(object sender, EventArgs e)
{
CreateControls();
UpdatePage();
}
protected void CreateControls()
{
Button button1 = new Button();
button1.ID = "_Button1";
button1.Text = "Button1";
button1.Click += new System.EventHandler(_ClickEvent);
_Panel.Controls.Add(button1);
Button button2 = new Button();
button2.ID = "_Button2";
button2.Text = "Button2";
button2.Click += new System.EventHandler(_ClickEvent);
_Panel.Controls.Add(button2);
}
protected void UpdatePage()
{
Button button1 = ((Button)_Panel.FindControl("_Button1"));
button1.Text = "I went through UpdatePage and changed";
Button button2 = ((Button)_Panel.FindControl("_Button2"));
button1.Text = "I went through UpdatePage and changed";
}
protected void _ClickEvent(object sender, EventArgs e)
{
}
Will try it:
protected String TextButton1
{
get { return (String) ViewState["TextButton1"]; }
set { ViewState["TextButton1"] = value; }
}
protected String TextButton2
{
get { return (String)ViewState["TextButton2"]; }
set { ViewState["TextButton2"] = value; }
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
CreateControls();
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
UpdatePage();
}
}
protected void CreateControls()
{
Button button1 = new Button();
button1.ID = "_Button1";
button1.Text = String.IsNullOrEmpty(TextButton1) ? "The First Value" : TextButton1;
button1.Click += new System.EventHandler(_ClickEvent1);
_Panel.Controls.Add(button1);
Button button2 = new Button();
button2.ID = "_Button2";
button2.Text = String.IsNullOrEmpty(TextButton2) ? "The First Value" : TextButton2;
button2.Click += new System.EventHandler(_ClickEvent2);
_Panel.Controls.Add(button2);
}
protected void UpdatePage()
{
Button button1 = ((Button)_Panel.FindControl("_Button1"));
button1.Text = String.IsNullOrEmpty(TextButton1) ? "The First Value" : TextButton1;
Button button2 = ((Button)_Panel.FindControl("_Button2"));
button2.Text = String.IsNullOrEmpty(TextButton2) ? "The First Value" : TextButton2;
}
protected void _ClickEvent1(object sender, EventArgs e)
{
TextButton1 = "test";
Button b = (Button) sender ;
b.Text = TextButton1;
}
protected void _ClickEvent2(object sender, EventArgs e)
{
TextButton2 = "test";
Button b = (Button)sender;
b.Text = TextButton2;
}

add a button click event dynamically in asp.net 4.5 c#

I have some questions to this post [1]: How can i create dynamic button click event on dynamic button?
The solution is not working for me, I created dynamically an Button, which is inside in an asp:table controller.
I have try to save my dynamic elements in an Session, and allocate the Session value to the object in the Page_Load, but this is not working.
Some ideas
edit:
...
Button button = new Button();
button.ID = "BtnTag";
button.Text = "Tag generieren";
button.Click += button_TagGenerieren;
tabellenZelle.Controls.Add(button);
Session["table"] = table;
}
public void button_TagGenerieren(object sender, EventArgs e)
{
TableRowCollection tabellenZeilen = qvTabelle.Rows;
for (int i = 0; i < tabellenZeilen.Count; i++)
{
...
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["table"] != null)
{
table = (Table) Session["table"];
Session["table"] = null;
}
}
}
It is not a good practice to store every control into Session state.
Only problem I found is you need to reload the controls with same Id, when the page is posted back to server. Otherwise, those controls will be null.
<asp:PlaceHolder runat="server" ID="PlaceHolder1" />
<asp:Label runat="server" ID="Label1"/>
protected void Page_Load(object sender, EventArgs e)
{
LoadControls();
}
private void LoadControls()
{
var button = new Button {ID = "BtnTag", Text = "Tag generieren"};
button.Click += button_Click;
PlaceHolder1.Controls.Add(button);
}
private void button_Click(object sender, EventArgs e)
{
Label1.Text = "BtnTag button is clicked";
}
Note: If you do not know the button's id (which is generated dynamically at run time), you want to save those ids in ViewState like this - https://stackoverflow.com/a/14449305/296861
The problem lies in the moment at which te button and it's event are created in the pagelifecycle. Try the page_init event for this.
Create Button in page load
Button btn = new Button();
btn.Text = "Dynamic";
btn.Click += new EventHandler(btnClick);
PlaceHolder1.Controls.Add(btn)
Button Click Event
protected void btnClick(object sender, EventArgs e)
{
// Coding to click event
}

Event does not fired when i create a button programatically

I was create a button dynamically with event handler. But the event not fired. Please help me to do this. My partial code is here.
Button btn = new Button();
btn.ID = "btn" + i;
btn.Text = "Add New";
Panel1.Controls.Add(btn);
btn.Click += new EventHandler(this.GreetingBtn_Click);
Panel1.Controls.Add(new LiteralControl("<br /><br />"));
void GreetingBtn_Click(Object sender, EventArgs e)
{
create();
}
I want to access the create() function when i click the button.
Without knowing much about your code, I'm guessing you're not creating the control in the appopriate stage of the page life cycle of ASP.NET
what you need is PreInit, as described here:
Raised after the start stage is complete and before the initialization stage begins.
Use this event for the following:
Create or re-create dynamic controls.
if you are adding this dynamic button on page load, make sure its under
if (!IsPostBack)
{
//add button here
}
always make your code of creating one time control that will made should be in side !ispostback because they are not need to be created again and again
if (!IsPostBack)
{
//Your code should be their enter code here
}
List<string> myControls = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
myControls = new List<string>();
ViewState["myControls"] = myControls;
}
}
protected void override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
myControls = (List<string>)ViewState["myControls"];
foreach(string controlID in myControls){
//method to create your buttons goes here.
createButtons(controlID);
}
}
public void createButtons(string btnID){
Button btn = new Button();
btn.ID = btnID;
btn.Text = "Add New";
btn.Click += new RoutedEventHandler(this.GreetingBtn_Click);
Panel1.Controls.Add(btn);
Panel1.Controls.Add(new LiteralControl("<br /><br />"));
}
void GreetingBtn_Click(Object sender, RoutedEventArgs e){
create();
}
Give this code a try. When adding controls dynamically in asp.net you have to recreate the controls in the postback. The easiest way to do this is using the viewstate as I showed above.
Common signs of not doing this correctly are: control disappears when you click it or event just doesn't fire at all. Hope this helps someone!
Move btn.Click += new EventHandler(this.GreetingBtn_Click); line one level up i.e. before adding to parent And try Routed events.
Button btn = new Button();
btn.ID = "btn" + i;
btn.Text = "Add New";
btn.Click += new RoutedEventHandler(this.GreetingBtn_Click);
Panel1.Controls.Add(btn);
Panel1.Controls.Add(new LiteralControl("<br /><br />"));
void GreetingBtn_Click(Object sender, RoutedEventArgs e)
{
create();
}

Programmatically create asp:Button and attach event in SharePoint

I'm trying to create ASP.NET buttons programmatically inside an update panel in my SharePoint instance, but because of the page life cycle, I can not attach server side events on buttons.
Here is the code:
TableCell tcellbutton = new TableCell();
b.Click += new EventHandler(b_Click);
b.CausesValidation = true;
tcellbutton.Controls.Add(b);
tr.Cells.Add(tcellbutton);
table.Rows.Add(tr);
panel1.Controls.Add(table);
void b_Click(object sender, EventArgs e)
{
string studentnumber = (sender as Button).ID.ToString().Substring(3, (sender as Button).ID.ToString().Length - 3);
TextBox t = panel1.FindControl("txt" + studentNumber) as TextBox;
}
Is there another way to create and attach buttons in Sharepoint?
Ok here is how I solved it, Thanks for all replies, I was looking for a way to attach an event to a button that is created dynamically during runtime (after initialization). Hope It works for others as well.
<script type="text/javascript">
function ButtonClick(buttonId) {
alert("Button " + buttonId + " clicked from javascript");
}
</script>
protected void Button_Click(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), ((Button)sender).ID, "<script>alert('Button_Click');</script>");
Response.Write(DateTime.Now.ToString() + ": " + ((Button)sender).ID + " was clicked");
}
private Button GetButton(string id, string name)
{
Button b = new Button();
b.Text = name;
b.ID = id;
b.Click += new EventHandler(Button_Click);
b.OnClientClick = "ButtonClick('" + b.ClientID + "')";
return b;
}
You should add your code in PreInit event, code below work good:
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
Button bb = new Button();
bb.Click += new EventHandler(bb_Click);
bb.CausesValidation = true;
bb.ID = "button1";
Panel1.Controls.Add(bb);
}
private void bb_Click(object sender, EventArgs e)
{
Response.Write("any thing here");
}
You are creating dynamic controls. Your code should execute in each PageLoad event.
Remove IsPostBack for the part of code where you are creating the buttons is my advice.
If you don't do this, you will create the controls, but each time when PageLoad event occurs, your control will be deleted and the application will not follow your events. With other words you should always recreate the controls.

Dynamic control and its Event

We are creating dynamic text boxes and buttons inside a grid for each row. Now we want to create click event for each button. To create button inside the grid in using ITemplate.
Code:
ImageButton imbtnAdd = new ImageButton();
imbtnAdd.ID = "imbtn" + columnName;
imbtnAdd.ImageUrl = "btn_add_icon.gif";
imbtnAdd.Width = 20;
container.Controls.Add(imbtnAdd);
Error:
I have used imbtnAdd.Click += new ImageClickEventHandler(imbtnAdd_Click); but it shows an error message
imbtnAdd_Click does not exist
ImageButton imbtnAdd = new ImageButton();
imbtnAdd.ID = "imbtn" + columnName;
imbtnAdd.ImageUrl = "btn_add_icon.gif";
imbtnAdd.Width = 20;
imbtnAdd.Click += imbtnAdd_Click;
container.Controls.Add(imbtnAdd);
// ...
private void imbtnAdd_Click(object sender, EventArgs e)
{
// handle event
}
Jrista's answer is correct.
Although, if you want to implement different handlers for all the buttons and you are using .Net 3.0 or above, you can use lambdas:
imbtnAdd.Click += (object sender, EventArgs e) =>
{
// Code handling code goes here...
};

Categories