2

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

it is working! and about better solution, could you explain me that a bit? Thans a lot!
@Roxy'Pro you should provide some more of what you have in terms of XAML and customersList, then I can try to explain possible changes.
ok I will provide it later, now I am wondering how can I put textbox + button in stackpanel but to keep it next to each other, If I set Orientation="Horizontal" than it looks ugly, should I open new question for this? Thanks again dude
@Roxy'Pro first, think of your desired layout (placement, size, ...) then ask yourself if a StackPanel is the right choice (you could use Grid, DockPanel, ...). If you know your desired layout, you will find ways to show it. Make sure that you research your stuff before asking a question about it - most things will already have an answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.