how to execute click event on dynamically created button in c#.net - c#

I am trying to build an app, where user can select category and according to it displays its sub categories , these sub categories are buttons, which are dynamically created.
Now, as buttons are dynamically created so I am confuse how to write code under button_click event as I dont know how many subcategories are there.
So is there any way I can execute click event of a particular button , so that I can execute certain commands?
EDITED
This is the code that i tried
Button btnDynamicButton = new Button();
private void btnclick_Click(object sender, EventArgs e)
{
label2.Text = btnDynamicButton.Text;
}
private void btnappetizer_Click(object sender, EventArgs e)
{
groupBox2.Visible =false;
DataTable dt = new DataTable();
dt = itemmasterbl.SelectallrecordFromtblItem(btnappetizer.Text);
for (int i = 0; i < dt.Rows.Count; i++)
{
string name = "Appetizer" + DynamicButtonCount;
Button btnDynamicButton1 = new Button();
btnDynamicButton1.Name = name;
btnDynamicButton1.Text = name;
btnDynamicButton1.Size =
new System.Drawing.Size(150, 30);
btnDynamicButton1.Location =
new System.Drawing.Point(180, DynamicButtonCount * 30);
btnDynamicButton1.Click +=new EventHandler(btnclick_Click);<br>
Controls.Add(btnDynamicButton1);
DynamicButtonCount++;
btnDynamicButton = btnDynamicButton1;
}
}
Once I do this it creates three buttons according to number of values in itemmaster DB under appetizer, but once I click on any of the three buttons the label displays only last buttons text,because in last line I have :
btnDynamicButton = btnDynamicButton1;
Which will last buttons infos,but rather I want which ever button I press, label should display respective text. How can I achieve this.

you can put all your logic into one handler:
System.Windows.Forms.Button b = new System.Windows.Forms.Button();
b.Click += new EventHandler(b_Click);
//finally insert the button where it needs to be inserted.
...
void b_Click(object sender, EventArgs e)
{
MessageBox.Show(((System.Windows.Forms.Button)sender).Name + " clicked");
}
To your edit:
You are storing the reference for your button(s) inside the Field btnDynamicButton. Hence it always gets overwritten with the latest button you have created. You should not reference the button by using a field. The sender parameter of the click-handler contains the button element that has been clicked. See the code above: Simple cast sender to Button and you know which button has been clicked:
private void btnclick_Click(object sender, EventArgs e)
{
Button btn = (Button)sender
label2.Text = btn.Text;
}

Related

How to create click event for dynamically created user controls in C#?

I'm creating a Windows Universal App which contains a ListView filled with User-Controls. User-Controls are added to ListView dynamically during runtime, based on the elements from the database.
public void ShowFavorites()
{
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), (Application.Current as App).DBPath))
{
var Favorites = conn.Table<Favorites>();
lvFavorites.Items.Clear();
foreach (var fav in Favorites)
{
FavoriteItem favItem = new FavoriteItem();
favItem.Favorite = fav;
lvFavorites.Items.Add(favItem);
}
}
}
So how can i create an event that that triggers when the user-control is pressed?
When you create the control, all you need to do is simply link the control to a new event:
// Dynamically set the properties of the control
btn.Location = new Point((lbl.Width + cmb.Width + 17), 5);
btn.Size = new System.Drawing.Size(90, 23);
btn.Text = "Add to Table";
// Create the control
this.Controls.Add(btn);
// Link it to an Event
btn.Click += new EventHandler(btn_Click);
Then, when you (in this case) click on the newly added button, it will call your btn_Click method:
private void btn_Click(object sender, EventArgs e)
{
//do stuff...
}
I got it working even for items with diffrent text etc.
I gonna explain it based on a button beeing added to a panel.
You need to have a List<> in which you store the items, in this case buttons.
List<Button> BtList = new List<Button>();
and I also have a Panel in this case.
Panel PanelForButtons = new Panel();
Here is my code I hope it helps you:
void AddItemToPanel()
{
//Creating a new temporary item.
Button TempBt = new Button();
TempBt.Text = "Hello world!";
//Adding the button to our itemlist.
BtList.Add(TempBt);
//Adding the event to our button.
//Because the added item is always the last we use:
PanelForButtons.Controls.Add(BtList.Last());
BtList.Last().Click += MyButtonClicked;
}
And here is the event:
void MyButtonClicked(object sender, EventArgs e)
{
//First we need to convert our object to a button.
Button ClickedButton = sender as Button;
//And there we have our item.
//We can change the text for example:
ClickedButton.Text = "The world says: \"Hello!\"";
}

Storing value in ASP.NET button

I have this code:
DataTable characterDataTable = character.getAllCharacters();
foreach(DataRow row in characterDataTable.Rows)
{
Button button = new Button();
button.Text = row["character"].ToString();
button.ID = row["character"].ToString() + "_btn";
button.Click = "character_btn_Click";
}
The characterDataTable returns 3 rows with a character and id column for instance char1, char2 and char3. Now I'm trying to create buttons depending on how many rows are retrieved and then trying to set a value to the button so when a button is clicked it will retrieve the value.. I want the value to be set as the ID of the row..
This is what I have at the moment:
protected void character_btn_Click(object sender, EventArgs e)
{
// Get value of clicked button
}
Does anyone know how to store a value in an ASP.NET button and retrieve it when it has been clicked?
To add a click handler to a Button, you should do this:
button.Click += character_btn_Click;
You can use CommandName to pass a "value" to the event handler. So the code becomes:
DataTable characterDataTable = character.getAllCharacters();
foreach(DataRow row in characterDataTable.Rows)
{
Button button = new Button();
button.Text = row["character"].ToString();
button.ID = row["character"].ToString() + "_btn";
button.CommandName = row["id"].ToString();
button.Click += character_btn_Click;
}
The click handler is then:
void character_btn_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
string value = btn.CommandName;
}

Change dynamic buttons text with textbox

Let me tell you what I want to do.
1.there are two button in my form.One of them let button when I click it.Another button finish to create button.
bool active = false;
private void button1_Click(object sender, EventArgs e)
{
active = true;
}
private void button2_Click(object sender, EventArgs e)
{
active = false;
}
2.I will create button with mousedown event I want to set location of this buttons with coordinate like this.
Button button_create;
private void frm_tr_MouseDown(object sender, MouseEventArgs e)
{
if (active)
{
button_create = new Button();
button_create.Location = new Point(e.X + 5, e.Y - 15);
button_create.Size = new Size(75, 30);
button_create.Text = "Button";
this.Controls.Add(button_create);
button_create.MouseClick += new MouseEventHandler(button_create_MouseClick);
}
}
3.I started mouseclickevent of my created button.When I click this created button I will create new form textbox and button.
TextBox button_text;
void button_create_MouseClick(object sender, MouseEventArgs e)
{
Form frm = new Form();
frm.Show();
button_text = new TextBox();
Button accept = new Button();
accept.Location = new Point(frm.Width / 2, frm.Height / 2);
frm.Controls.Add(button_text);
frm.Controls.Add(accept);
accept.MouseClick += new MouseEventHandler(accept_MouseClick);
}
4.I started mouseclickevent of my last created button.I want to change text of my first created button.
void accept_MouseClick(object sender, MouseEventArgs e)
{
button_create.Text = button_text.Text;
}
5.I will click button1 and I click anywhere of this form new button will create and I also click button2 to finish create new button.I can change my created button with textbox but
If I click button1 and I create a new one button I cant change text of previous created button How can I do that?

c# add button event programmatically

Trying to add buttons programmatically to a webform.
Some work - others don't.
In the code below I add btnY and btnX in the Page_Load.
These both work - they show on the page and fire the event
and the code in the event handler works....
In the page load I also run bindData which gets a DataTable
and uses the data to create controls.
in the example I am only creating Button.
These buttons will appear on the page correctly but when clicked
they only do a postback ..
the code in the event handler doesn't work - does it get called?
The event handler is the same for all the buttons.
Any ideas why or how I can make it work?
protected void Page_Load(object sender, EventArgs e)
{
PlaceHolder1.Controls.Add(btn("btnY", "Y"));
Pages P = new Pages();
bindData(P.DT);
PlaceHolder1.Controls.Add(btn("btnX", "X"));
}
Button btn(string id, string text)
{
Button btn1 = new Button();
btn1.ID = id;
btn1.Text = text;
btn1.Click += new System.EventHandler(this.btn_click);
return btn1;
}
protected void bindData(DataTable dt)
{
foreach (DataRow row in dt.Rows)
{
render(Convert.ToInt32(row["PageKey"]));
}
}
protected void render(int pageKey)
{
PlaceHolder1.Controls.Add(btn("btn_" + pageKey.ToString(), "Edit"));
}
protected void btn_click(object sender, EventArgs e)
{
Button btn = (Button)sender;
string id = btn.ID;
Pages P = new Pages();
bindData(P.DT);
lt.Text = "ID=" + id;
}
Never mind .. figured it out .. example above should work, my actual code had a if (!Page.PostBack) that caused the problem

Dynamic generation of buttons with their click event

I am doing following code to generate dynamic buttons with their click event.
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < int.Parse(TextBox1.Text); i++)
{
Button bt = new Button();
bt.Text = "ok";
bt.Click += new EventHandler(bt_click);
this.form1.Controls.Add(bt);
}
}
protected void bt_click(object sender, EventArgs e)
{
Label1.Text = "Clicked";
}
but i am not able to generate the click event of that dynamically generated button.
Can any one help me?
For ASP.NET to be able to execute your event, control which triggered it should also exist on your page after postback. What is going on with your code looks like this:
page has several buttons you placed in design mode
you click button which generates new buttons
page loads again and looks for button you clicked, in the page
button is found, asp looks for event handler and executes it
new dynamic buttons are added and events attached, page renders again
It was all ok up till now, now problem occurs
you click button which was added dynamically
page loads again and looks for button you clicked (so it can find it's handler)
button is not found because it is not created yet. it was created dynamically to be rendered, and it wasn't created after postback at stage where asp is looking for it
General rule is that if you're adding controls dynamically and you want them to trigger events, you should do it latest in Page_Load.
For more details please read ASP.NET Page Life Cycle Overview
My previous submission was on WinForms which I have deleted. Here is the one on asp.net
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
for (int i = 0; i < int.Parse(TextBox1.Text); i++)
{
CreateButton(i);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void bt_click(object sender, EventArgs e)
{
Button btn = sender as Button;
Label1.Text = btn.Text + " Clicked";
}
private void CreateButton(int id)
{
Button bt = new Button();
bt.Text = "ok" + id.ToString();
bt.Click += new EventHandler(bt_click);
bt.ID = "btn" + id.ToString();
this.Form.Controls.Add(bt);
}
You need to set the position of those new buttons, or they will cover each other.
I'm not sure if its your problem, but you might want to set the location property of eachbutton you add like:
bt.Location = new Point(25,i+55);
you need to add this code in either page load or page_init event of page. then only you can access it. How to add controls dynamically asp.net
protected void Page_Load()
{
for (int i = 0; i < int.Parse(textBox1.Text); i++)
{
Button bt = new Button();
bt.Text = "ok";
bt.Click += new EventHandler(bt_click);
this.Controls.Add(bt);
}
}

Categories

Resources