Wire up button created at runtime - asp.net

Im creating some buttons based on a value of some runtime variable (i dont even know how many).
My code for the button is as follows:
Button cancel = new Button();
cancel.Text = "Cancel";
cancel.ID = "cancelEnrollmentForStudent" + zapsanePredmetyList.ElementAt(i).ID.ToString() + "-" + i ;
cancel.Click += new EventHandler(cancelEnrollment);
string toCancel = selectedSubject.SelectedValue + ";" + studentToEnroll.SelectedValue;
cancel.CommandArgument = toCancel;
while the code for the click method is
protected void cancelEnrollment(object sender, EventArgs e)
{
//do something when button clicked.
Button sourceButton = (Button)sender;
string[] data = sourceButton.CommandArgument.Split(';');
}
However, the click method is not firing up when the button is clicked. I suppose this has something to do with the fact, that I build the button at runtime. Cld someone advise on how to get this method fire up?
Thanks,
Ondrej

You have to override OnInit add the code in OnInit method.
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Button btn = new Button();
btn.ID = "btn1";
btn.Text = "Button1";
btn.Click += new EventHandler(btn_Click);
this.form1.Controls.Add(btn);
}
void btn_Click(object sender, EventArgs e)
{
Button bt = (Button)sender;
bt.Text = "Changed";
}

Related

ASP.NET dynamically added button click event doesnt work

In my webform app I have gridview with SQLDataSource. Now, I need to add button dynamically into one cell of each row (button must have value of cell) of this gridview. I added button for each cell, and also added click event for these buttons. But when I click these buttons click event doesn't work. Can everyone help?
protected void gvEmployee_RowDataBound(object sender, Obout.Grid.GridRowEventArgs e)
{
Button btn = new Button();
btn.Text = e.Row.Cells[8].Text;
if (e.Row.Cells[8].Text == "1")
{
btn.BackColor = Color.Red;
}
else
{
btn.BackColor = Color.Green;
}
e.Row.Cells[8].Text = "";
btn.Click += btn_Click;
e.Row.Cells[8].Controls.Add(btn);
}
protected void btn_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}

Dynamically generating buttons in ASP.NET and passing values to Codebehind

I'm using a foreach loop to generate content how do I listen for a button click to call codebehind function. I can't set a value for a ASP button. How should I go about this ? When the user clicks on a button I want the ID for the user they clicked on to get passed to codebehind
You can pass the ID in the CommandArgument property of a button and you can assign the onclick event all inside the loop:
//for loop
//...
Button btn = new Button();
//etc
btn.CommandArgument = theID;
btn.Click += new EventHandler(btn_Click);
//...
//end for loop
protected void btn_Click(object sender, EventArgs e)
{
//Need to know which btn was clicked
Button btn = sender as Button;
if(btn == null)
{
//throw exception, etc
}
int id = Convert.ToInt32(btn.CommandArgument);
//etc
}
You can use Runtime generated Button Id to pass values to it.
//Counter for Dynamic Buttons.
int DynamicButtonCount = 1;
//This event generates Dynamic Buttons.
private void btnGenerate_Click(object sender, EventArgs e)
{
string name = "Dynamic Button_" + DynamicButtonCount;
Button btnDynamicButton = new Button();
btnDynamicButton.Name = name;
btnDynamicButton.Text = name;
btnDynamicButton.Id= DynamicButtonCount; //Use this id value
btnDynamicButton.Size = new System.Drawing.Size(200, 30);
btnDynamicButton.Location = new System.Drawing.Point(40, DynamicButtonCount * 40);
btnDynamicButton.Click += new EventHandler(this.btnDynamicButton_Click);
Controls.Add(btnDynamicButton);
DynamicButtonCount++;
}
//This event is triggered when a Dynamic Button is clicked.
protected void btnDynamicButton_Click(object sender, EventArgs e)
{
Button dynamicButton = (sender as Button);
MessageBox.Show("You clicked. " + dynamicButton.Name);
}

why my function doesn't execute after clicking dynamically created button

here is my scenarioton : if !page.Ispostback i fill a dropdown with data from database!
Also in the page there is a butron and onclick it gets one id from database and crates one panel IN WHIH THERE IS DYNAMICALLY CREATED BUTTON. The PROBLEM IS WHEN I CLICK THIS DYNAMICALLY CREATED BUTTON _ JUST NOTHING HAPPENS AND I CANT EXPLAIN WHY.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlLanguages.DataSource = this.catRep.GetAllAvailableLanguages();
ddlLanguages.DataBind();
}
//IEnumerable<CatgoriesLanguages> allcategories = this.catRep.GetAllCategoriesByID(1)
}
protected void btnAddNew_Click(object sender, EventArgs e)
{
inseredID = this.catRep.AddCategory();
Label mylab = new Label();
mylab.Text = "Yeeee" + inseredID;
Page.FindControl("form1").Controls.Add(mylab);
Panel myFieldSet = new Panel();
myFieldSet.GroupingText= "Add New Category";
Label lblTitle = new Label();
lblTitle.Text="Title: ";
myFieldSet.Controls.Add(lblTitle);
TextBox txbTitle = new TextBox();
txbTitle.ID = "txbTitle";
myFieldSet.Controls.Add(txbTitle);
myFieldSet.Controls.Add(new LiteralControl("<br />"));
Label lblShrtDescrpt = new Label();
lblShrtDescrpt.Text = "Short Description: ";
myFieldSet.Controls.Add(lblShrtDescrpt);
TextBox txbShrtDescrpt = new TextBox();
txbShrtDescrpt.ID = "txbShrtDescrpt";
myFieldSet.Controls.Add(txbShrtDescrpt);
myFieldSet.Controls.Add(new LiteralControl("<br />"));
Label lblDescrpt = new Label();
lblDescrpt.Text = "Description: ";
myFieldSet.Controls.Add(lblDescrpt);
TextBox txbDescrpt = new TextBox();
txbDescrpt.ID = "txbDescrpt";
myFieldSet.Controls.Add(txbDescrpt);
Button btnAddcategorieslanguage = new Button();
btnAddcategorieslanguage.Click += new EventHandler(btnAddcategorieslanguage_Click);
myFieldSet.Controls.Add(btnAddcategorieslanguage);
Page.FindControl("form1").Controls.Add(myFieldSet);
}
public void btnAddcategorieslanguage_Click(object sender, EventArgs e)
{
TextBox txbTitle = (TextBox)FindControl("txbTitle");
TextBox txbShrtDescrpt = (TextBox)FindControl("txbShrtDescrpt");
TextBox txbDescrpt = (TextBox)FindControl("txbDescrpt");
this.catRep.AddCategoriesLanguages(11, 2, "malee", "tariiiiii", "liliiii");
}
You need to create all dynamically added controls in page Init or page load event too.
Something like this:
protected void Page_Load(object sender, EventArgs e)
{
if(ThereIsDynamicControl())
{
//You can set some session or viewState in the btnAddNew_Click to determine whether you need to add dynamic controls again here or not.
}
if (!IsPostBack)
{
ddlLanguages.DataSource = this.catRep.GetAllAvailableLanguages();
ddlLanguages.DataBind();
}
//IEnumerable<CatgoriesLanguages> allcategories = this.catRep.GetAllCategoriesByID(1);
}

Asp.net create LinkButton and attach onclick event when another LinkButton is clicked

So.. I'm dynamically creating LinkButtons on my page like this:
LinkButton lb = new LinkButton();
lb.Click += new EventHandler(lb_Click);
When one of these LinkButtons is clicked, I need to know which one the links was clicked, then create another LinkButton and attach an onclick event on it. (How) can I do this? If I have understood correctly, click events can't be attached in (this case in) lb_Click function, so is there any way I still could do this?
Edited:
To make this problem more understandable, here's how I tried to make it but it does not work:
LinkButton lb = new LinkButton();
lb.click += new EventHandler(lb_Click);
void lb_Click(object sender, EventArgs e)
{
LinkButton lb2 = new LinkButton();
lb2.click += new EventHandler(lb2_Click);
}
void lb2_Click(object sender, EventArgs e)
{
//do something
}
Clicking lb2 does not fire the lb2_Click event.
You can try with this code - based on sender argument
LinkButton lb = new LinkButton();
lb.Id= "Test1";
lb.Click += new EventHandler(lb_Click);
LinkButton lb2 = new LinkButton();
lb2.Id= "Test2";
lb2.Click += new EventHandler(lb_Click);
void LinkButton_Click(Object sender, EventArgs e)
{
var yourControl = (LinkButton)sender;
var id = yourControl.Id;
if(id == "Test1")
{
...
}
else if(id == "Test2")
{
...
}
}
Yes, yes, yes: I'm very, very late to the party.
BUT for future reference of anyone coming to this post:
Your methods are marked as private (omitting an access modifier defaults to private), which means they are not accessible enough for them to be called.
Instead, use the protected modifier to ensure they get called properly.
Like so:
LinkButton lb = new LinkButton();
lb.click += new EventHandler(lb_Click);
protected void lb_Click(object sender, EventArgs e)
{
LinkButton lb2 = new LinkButton();
lb2.click += new EventHandler(lb2_Click);
}
protected void lb2_Click(object sender, EventArgs e)
{
//do something
}
Hope this helps some future visitors :)

Event Control Not working?

i careate button control and place in panel but not working?
protected void Button1_Click(object sender, EventArgs e)
{
Button btn = new Button();
btn.Text = "Test button";
Panel1.Controls.Add(btn);
btn.Click += new EventHandler(btn_Click);
}
void btn_Click(object sender, EventArgs e)
{
Response.Write("<script>alert('test')</script>");
}
When you dynamically add controls to your page, you have to re-add them on any subsequent request (postback). The button you added in Button1_OnClick will not automatically be recreated in a subsequent request (e.g. in a postback).
There a lot's of similar questions about this topic, where you can find details. For examples, use the following search:
https://stackoverflow.com/search?q=dynamic+control+event+[asp.net]
Make sure you assign an ID to the button, and make sure it's the same everytime you create it.
Create the control in the CreateChildControls overload, adding it once in response to another event isn't going to be enough to keep it on the page.
You're best bet is going to be tracking the whether the button needs to be created or not:
bool CreateButton
{
get
{
if (ViewState["CreateButton"] == null)
return false;
return (bool)ViewState["CreateButton"];
}
set
{
ViewState["CreateButton"] = value;
}
}
override void public CreateChildControls ()
{
panel1.Controls.Clear ();
if (CreateButton)
{
Button btn = new Button();
btn.Text = "Test button";
btn.ID = "CreatedButton"; // Note the ID here...
Panel1.Controls.Add(btn);
btn.Click += new EventHandler(btn_Click);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
CreateButton = true;
EnsureChildControls ();
}
void btn_Click(object sender, EventArgs e)
{
Response.Write("<script>alert('test')</script>");
}
Something like that should work for you...

Resources