Dynamically generated Button click not getting called? - c#

I have associated a Button ID while generating Buttons dynamically and created a Button event handler as follows:
btn.Click += new EventHandler(btn_Click);
Button Click event:
protected void btn_Click(object sender,EventArgs e)
{
Button b = new Button();
b = (Button)sender;
string i = b.ID.Substring(b.ID.Length - 1, 1);
int j1 =Convert.ToInt32(i);
id1 = to[j1];
Page.ClientScript.RegisterClientScriptBlock(Type.GetType("System.String"),
"addScript", "PassValues('" + id1 + "')", true);
ScriptManager.RegisterStartupScript(this, this.GetType(),
"sendMessage", "javascript:sendMessage(); ", true);
}
However this event is not getting called i have placed all my controls inside an UpdatePanel
EDIT: What is happening is on button click somehow a function is getting called which is present on Page.Load
protected void getEntriesRight()
{
j = (int)Session["j"];
int n1 = j + 3;
for (; j <= n1; j++)
{
if (j < fr.data.Length)
{
HtmlGenericControl listItem = new HtmlGenericControl("li");
HtmlGenericControl a1 = new HtmlGenericControl("a");
Label anchor = new Label();
Image im = new Image();
btn = new Button();
im.ImageUrl = fr.data[j].pic_square;
im.Height = 45;
im.Width = 47;
btn.CssClass = "btn-add";
btn.Text = "Invite";
to[j] = fr.data[j].uid;
btn.ID = "btn" + j;
a1.Attributes.Add("href", "#");
anchor.Text = fr.data[j].name;
a1.Controls.Add(btn);
a1.Controls.Add(im);
a1.Controls.Add(anchor);
listItem.Controls.Add(a1);
list.Controls.Add(listItem);
btn.Click += new EventHandler(btn_Click);
}
}
Session["j"] = j;
}
Help!

Dynamically generated controls have to be recreated on every postback in order for their events to fire. This is one of the most commonly-encountered problems with generating controls programmatically in .NET, and it is discouraged if you can find a way around it.
For example, if you have a button that should only be present when another button is clicked, have the button in the page to begin with, and use the Visible property to control whether it is shown or not.
Regarding your edit. Every post-back to the server, even inside an UpdatePanel, is going to call Page_Load. If you want to detect whether a request has come from an UpdatePanel then you need to check !Page.IsAsync before calling the function.

Related

How to dynamically create buttons and to add different event handler?

I created a function that appends buttons in a form. Buttons when clicked supposed to open different files. File paths are in listbox1. I want to add a click event for every button I append. One button should open one file from listbox1.
The part with appending buttons works, but I can't add a different event for each of them only one.
This is my code. It adds the event to every button but only the last one.
PlaySong is a function that plays ".mp3" file. That works.
Can someone help me?
int i = 0;
private void Load_Songs()
{
List<string> url = new List<string>();
url = listBox1.Items.Cast<String>().ToList();
int p = 5;
for (int j = 0; j < listBox1.Items.Count; j++)
{
EventHandler klik = new EventHandler(Playing);
Song_Data titl = new Song_Data(url[j]);
Button n = new Button
{
Text = titl.Title,
Location = new Point(0, p + 20),
Width = ClientRectangle.Width / 3,
FlatStyle = FlatStyle.Flat
};
p += 20;
n.Click += klik;
List_Artist.Controls.Add(n);
i++;
}
}
private void Playing(object sender, EventArgs e)
{
PlaySong(listBox1.Items[i].ToString());
}
You don't need many event handlers, just store the index to the button's Tag in your loop and then use it to find which index you should use to choose from listbox:
Button n = new Button
{
Text = titl.Title,
Location = new Point(0, p + 20),
Width = ClientRectangle.Width / 3,
FlatStyle = FlatStyle.Flat,
Tag = j
};
Then in your handler:
private void Playing(object sender, EventArgs e)
{
int i= (int)((Button)sender).Tag;
PlaySong(listBox1.Items[i].ToString());
}
to use different handler for each button you can use anonymous event handler, but won't solve your problem:
n.Click += (s, ev) =>
{
//code when button clicked
};

How to automatically Click button during runtime using C# [duplicate]

This question already has answers here:
How can I programmatically call my .net button's onclick in page load?
(5 answers)
Closed 5 years ago.
I have created 100 buttons and want to first button clicked by default when page load first time(without clicking on button).
HtmlTable myTable = new HtmlTable();
int n = 0;
for (int i = 0; i < 20; i++)
{
HtmlTableRow row = new HtmlTableRow();
for (int c = 1; c <= 5; c++)
{
n = (5 * i) + c;
HtmlTableCell cell = new HtmlTableCell();
Button btn = new Button();
btn.Text = n.ToString();
btn.ID = n.ToString();
//btn.BackColor = Color.Transparent;
btn.Width = 30;
btn.Height = 25;
btn.Click += new EventHandler(btn_Click);
cell.Controls.Add(btn);
row.Controls.Add(cell);
myTable.Controls.Add(row);
cell.Attributes.Add("Class", "htTableCellCss");
}
row.Attributes.Add("Class", "htTableRowCss");
}
myTable.Attributes.Add("Class", "htTableCss");
btndiv.Controls.Add(myTable);
Well, before you start coding, place yoursef in protected void Page_Load method
and there you should just call the onlick method event directly, like this ( lets say yyour button is named myButton, and lets say it's allready defined what's that gonna do):
myButton_Click(this, EventArgs.Empty);
You can place this method invokation exactlly where you need it, so on your page load also

Change properties of programmatically created buttons

I create buttons in my application by:
List<Button> btnslist = new List<Button>();
for (int i = 0; i < nbrofbtns; i++)
{
Button newButton = new Button();
btnslist.Add(newButton);
this.Controls.Add(newButton);
newButton.Width = btnsidelength;
newButton.Height = btnsidelength;
newButton.Top = btnsidelength
* Convert.ToInt32(Math.Floor(Convert.ToDouble(i / Form2.puzzlesize)));
newButton.Left = btnsidelength
* Convert.ToInt32(
Math.Floor(Convert.ToDouble(i))
- Math.Floor((Convert.ToDouble(i))
/ (Form2.puzzlesize)) * (Form2.puzzlesize));
newButton.BackgroundImage = Lights_out_.Properties.Resources.LightsOutBlack;
newButton.Tag = (i+1).ToString();
newButton.Click += new EventHandler(Any_Button_Click);
Then I have a method for when any of the buttons are clicked.
void Any_Button_Click(object sender, EventArgs e)
{
//the variable b has all the insformation that the single button had itself.
Button b = (Button)sender;
if (b.BackgroundImage == Lights_out_.Properties.Resources.LightsOutBlack)
{
MessageBox.Show(b.Tag.ToString());
MessageBox.Show(btnslist[Convert.ToInt32(b.Tag)].BackgroundImage.ToString());
btnslist[Convert.ToInt32(b.Tag)].BackgroundImage =
Lights_out_.Properties.Resources.LightsOutWhite;
MessageBox.Show(btnslist[Convert.ToInt32(b.Tag)].BackgroundImage.ToString());
}
else
{
MessageBox.Show("b.backgroundimage != lightsoutblack. Backgroundimage = "
+ b.BackgroundImage.ToString());
}
}
How do I change the data in the actual button (then said button is clicked)? I want specificly to change the backgroundimage. How could I do this?? (I also need to change the backgroundimage of some other buttons created by the code.)
The sender object is the button:
Button b = (Button)sender;
... so you should be able to change properties on it directly:
b.WhateverPropsToChange = yourSetting;
PS: I don't think this is necessary, but if the button is not updated directly, you might try to using b.Refresh() to let it know something has changed.
You're handling Click event of every button you've created - and sender in Any_Button_Click is actually the button was clicked.
So just change b.BackgroundImage to whatever you need.

Why is my second subButton not working?

This web page create controls.
First control "Parent"
Second control "child". Child button creates by parent. But i have one problem, Page doesn't respond child event(((
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication14
{
public partial class WebForm1 : System.Web.UI.Page
{
private Button[] buttons = new Button[256];
protected void Page_Load(object sender, EventArgs e)
{
Maybe i have a problem with this section???
for (int i = 0; i < 10; i++) // Create 10 buttons
{
buttons[i] = new Button(); // New button
buttons[i].ID = "Button" + i; // Button id
buttons[i].Text = "Button " + i; // Button text
I don't know why this event not work propertly
buttons[i].Click += (c, cArgs) => //Set Event
{
TextBox1.Text += "Hi"; //Doesn't show me result.Why???
};
}
int val = 0;
Button b = new Button(); // Create new button
b.ID = "BT1"; // Set button id "BT1"
b.Text = "Click"; // Set on button text
form1.Controls.Add(b); // add this button to form1
b.Click += (k, kArgs) => // Give this button event with parameters
{
val = Convert.ToInt32(TextBox1.Text); // Convert value of TextBox1 to int32 and set this value to variable "val"
form1.Controls.Add(buttons[val]); // Add subButton by value seted on variable "Val"
};
}
}
}
I believe that it is best to have all UI objects and their events bound/added to the form at the beginning before the page is completely loaded (Page_Load), preferably at page initialization (Page_Init). Your current approach doesn’t bind the button's click event correctly because it’s happening after Page_Load after a click event occurs on button 'b'. To alleviate this, you should add ALL UI objects during Page_Init or if you must Page_Load BUT you can control their visibility instead. This way you can guarantee that all objects have their events bound to the form correctly:
C# Code-Behind:
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++) // Create 10 buttons
{
buttons[i] = new Button(); // New button
buttons[i].ID = "Button" + i; // Button id
buttons[i].Text = "Button " + i; // Button text
buttons[i].Click += (c, cArgs) => //Set Event
{
TextBox1.Text += "Hi";
};
buttons[i].Visible = false; // Set visibility to false
form1.Controls.Add(buttons[i]); // Add button to form1
}
int val = 0;
Button b = new Button(); // Create new button
b.ID = "BT1"; // Set button id "BT1"
b.Text = "Click"; // Set on button text
form1.Controls.Add(b); // add this button to form1
b.Click += (k, kArgs) => // Give this button event with parameters
{
val = Convert.ToInt32(TextBox1.Text); // Convert value of TextBox1 to int32 and set this value to variable "val"
buttons[val].Visible = true; // Set visibility to true
};
}

Click event for dynamically created link buttons not firing?

This is application i am doing in c# web application
I am creating link buttons dynamically as below.
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
LinkButton ln = new LinkButton();
ln.Text = ds.Tables[0].Rows[i].ItemArray[0].ToString();
ln.ID = ds.Tables[0].Rows[i].ItemArray[1].ToString();
divonlne.Controls.Add(ln);
divonlne.Controls.Add(new LiteralControl("<br/>"));
}
my click event is as follows
ln.Click += new EventHandler(Clicked);
In my click event i am getting the linkbutton text and Id as follows
protected void Clicked(object sender, EventArgs e)
{
LinkButton lno = sender as LinkButton;
Session["Toname"] = lno.Text;
Session["idto"] = lno.ID;
}
But this is firing only when the last link button is clicked.
Can anyone help me out?
You already wrote how you subscribe the Click Event, but in your sample i cant see it.
Maybe you subscribe on the wrong place. This works...
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
LinkButton ln = new LinkButton();
ln.Text = ds.Tables[0].Rows[i].ItemArray[0].ToString();
ln.ID = ds.Tables[0].Rows[i].ItemArray[1].ToString();
ln.Click += new EventHandler(Clicked);
divonlne.Controls.Add(ln);
divonlne.Controls.Add(new LiteralControl("<br/>"));
}
When using dynamic controls in a custom control, remember to decorate your class with the INamingContainer interface. This ensures recreated controls fit correctly into the hierarchy and remember which events they are supposed to handle.

Categories