locked
Windows store app - button onCick event RRS feed

  • Question

  • I am using a for loop to create 4 buttons. How do i set an onClick even handler to them while i create them in the loop?

    They should all go to the same method when they are clicked.

    Sunday, January 5, 2014 7:43 AM

Answers

  • See How to add a button

    In the loop add the event handler to each button you create: NewButton.Click += MyButtonEventHandler;

    • Marked as answer by kalel111 Monday, January 6, 2014 4:41 AM
    Sunday, January 5, 2014 9:50 AM
    Moderator
  • Hello kalel111, 

    try to use this method :

    for (int i = 0; i < 4; i++) { Button btn = new Button(); btn.Name = "btn" + i; btn.Click += btn_Click;

    grid1.Children.Add(btn); } private void btn_Click(object sender, RoutedEventArgs e) { Button btn = (Button)sender; switch (btn.Name) { case "btn0": //first button clicked. break; case "btn1": //second button clicked. break; } }



    • Edited by Khant Nipun Monday, January 6, 2014 4:35 AM
    • Marked as answer by kalel111 Monday, January 6, 2014 4:41 AM
    Monday, January 6, 2014 4:34 AM

All replies

  • See How to add a button

    In the loop add the event handler to each button you create: NewButton.Click += MyButtonEventHandler;

    • Marked as answer by kalel111 Monday, January 6, 2014 4:41 AM
    Sunday, January 5, 2014 9:50 AM
    Moderator
  • Hello kalel111, 

    try to use this method :

    for (int i = 0; i < 4; i++) { Button btn = new Button(); btn.Name = "btn" + i; btn.Click += btn_Click;

    grid1.Children.Add(btn); } private void btn_Click(object sender, RoutedEventArgs e) { Button btn = (Button)sender; switch (btn.Name) { case "btn0": //first button clicked. break; case "btn1": //second button clicked. break; } }



    • Edited by Khant Nipun Monday, January 6, 2014 4:35 AM
    • Marked as answer by kalel111 Monday, January 6, 2014 4:41 AM
    Monday, January 6, 2014 4:34 AM