Get object/item on button click (dynamically created button) - stack panel - c#

I am looping my customers, and for each customer I need to create one button in case
I would like to delete that specific customer.
So here is my code:
foreach (var item in customersList)
{
Button btn = new Button();
btn.Content = "Customer": + " " + item.Value;
btn.Height = 40;
btn.Click += btn_Click;
TextBox cust = new TextBox();
cust.Height = 40;
cust.Text = item.Value;
stackCustomers.Children.Add(cust);
stackCustomers.Children.Add(btn);
}
How could I attach event Click on my button so when I click on It I get customer?
void btn_Click(object sender, RoutedEventArgs e)
{
//I tried this but it is not working, unfortunatelly...
Customer cust = (Customer)sender;
}

The easy way: attach customer to the Button.Tag property
Button btn = new Button();
btn.Tag = item; // .Value maybe?
// ...
void btn_Click(object sender, RoutedEventArgs e)
{
var button = sender as Button;
Customer cust = (Customer)button.Tag;
}
What might be better: Create a visual representation of each customer item, where the button is contained. Use Button.Command and Button.CommandParameter={Binding PathToCustomer} instead of Button.Click.

Related

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;
}

C# Dynamic button not firing click event

It reloads the page empty when I click the button. How do I fire click event on button click? I think Page.IsPostBack is the reason it reloads the page empty instead of showing the label.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
account account = new account();
accountManager accountManager = new accountManager();
group group = new group();
groupManager groupManager = new groupManager();
string emailAddress;
emailAddress = HttpContext.Current.User.Identity.Name;
account = accountManager.getAccInfoByEmailAddress(emailAddress);
group = groupManager.getGroupLeader(account.groupNo);
if (account.groupNo == 0)
{
divMessage.InnerHtml = "You are not in any group.";
}
else
{
try
{
Button btn = new Button();
btn.Text = "Click";
btn.Click += new EventHandler(button_Click);
form1.Controls.Add(btn);
}
catch (Exception)
{
divMessage.InnerHtml = "Unable to retrieve data. Please contact administrator if the problem persists.";
}
}
}
}
.
private void button_Click(object sender, EventArgs e)
{
Label Label1 = new Label();
Label1.Text = "rthfg";
form1.Controls.Add(Label1);
}
When you click the button, or somehow else generate a postback, ASP.NET creates the page (as it always does) and tries to find the source of the request, that is the button you clicked. In your case this button is no longer on the page, so ASP.NET cannot find anything, end does not fire the event.
Resolution seems easy enough in your case - just always create the button and put it on the page, regardless of the postback:
if (!Page.IsPostBack)
{
...
}
Button btn = new Button();
btn.Text = "Click";
btn.Click += new EventHandler(button_Click);
form1.Controls.Add(btn);
Btw, why make the button dynamic? Dynamic controls are always harder to manage.

Create buttons dynamically in asp.net page and fire click event to all buttons

I want to create buttons dynamically in asp.net page and wrote the code. Buttons created dynamically through below code.
List<string> category = new List<string>();
category.Add("AAA");
category.Add("BBB");
category.Add("CCC");
category.Add("DDD");
category.Add("EEE");
for (int i = 0; i < category.Count; i++)
{
TableRow tr = new TableRow();
TableCell cl = new TableCell();
TableCell cl2 = new TableCell();
Button button = new Button();
button.ID = "raid" + i;
button.Text = category[i];
button.Click +=button_Click;
private void button_Click(object sender, EventArgs e)
{
Response.Write(sender.ToString());
}
Now I want to add click events for all buttons and want to get which button click event has been fired.
Any idea?
Response.Write(sender.ToString()); OR Response.Write(e.ToString()); returns common properties.
You can use CommandArgument property.
button.ID = "raid" + i;
button.Text = category[i];
button.Click +=button_Click;
button.CommandArgument +=category[i];
private void button_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
string category = btn.CommandArgument;
}

WPF / C# - Adding functionality to a button dynamically created inside a listbox

I have a button that adds this StackPanel to the listbox everytime it's clicked. In it is a button. I'm trying to figure out how to add code to this button that it's adding. Ideally I want the button to be a delete button, so it would delete that element (itself) in the list. I'm just trying to figure out how to add functionality to the button I'm dynamically creating. hope that makes sense
thanks for any help!
private void Button_Click_1(object sender, RoutedEventArgs e)
{
StackPanel stackPanel = new StackPanel();
stackPanel.Orientation = System.Windows.Controls.Orientation.Horizontal;
CheckBox checkBox = new CheckBox();
checkBox.IsChecked = true;
TextBox textBox = new TextBox();
textBox.Width = 100;
textBox.Text = textBox1.Text;
Button button = new Button(); //HOW DO I ADD CODE TO THIS BUTTON?
stackPanel.Children.Add(checkBox);
stackPanel.Children.Add(textBox);
stackPanel.Children.Add(button); //HOW DO I ADD CODE TO THIS BUTTON?
listBox1.Items.Add(stackPanel);
}
You can programatically add a click handler to the button like this:
Button button = new Button(); //HOW DO I ADD CODE TO THIS BUTTON?
button.Click += btn_Click;
stackPanel.Children.Add(checkBox);
stackPanel.Children.Add(textBox);
stackPanel.Children.Add(button); //HOW DO I ADD CODE TO THIS BUTTON?
and then you need the click event handler
void btn_Click(object sender, System.Windows.RoutedEventArgs e)
{
// your code to execute when the button is clicked.
stackPanel.Items.Remove(button);
}
Try This.
Add Stackpanel that have textblock and Button
private void OnSaveClick(object sender, RoutedEventArgs e)
{
StackPanel stp = new StackPanel();
stp.Orientation = Orientation.Horizontal;
stp.Children.Add(new TextBlock()
{
Text = string.Format("Item {0}", lstitems.Items.Count),
HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch
});
Button btn = new Button();
btn.Content = string.Format("Delete Item {0}", lstitems.Items.Count);
btn.Height = 25;
btn.Width = 100;
btn.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
btn.Click += btnDeleteClick;
stp.Children.Add(btn);
lstitems.Items.Add(stp);
}
Delete Button Click handler
void btnDeleteClick(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
if (btn != null)
{
var st = FindParent<StackPanel> (btn); //stackpanel as we have added item as stackpanel.
if (st != null)
lstitems.Items.Remove(st);
}
}
To Find the Type to Object in the Visual Tree.
public T FindParent<T>(DependencyObject dependencyObject) where T : DependencyObject
{
var parent = VisualTreeHelper.GetParent(dependencyObject);
if (parent == null) return null;
var parentT = parent as T;
return parentT ?? FindParent<T>(parent);
}
That is the simplest setup. Ideally you want more error handling etc.
Button button = new Button();
button.Click += (s, args) => { listBox1.Items.Remove(stackPanel); };

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

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;
}

Categories

Resources