Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you associate click events of buttons created in code in C# with methods?

I'm building a Windows Phone app and I can't make a dynamically created Button associate with its event handler.

The code I'm using is:

public partial class MainPage : PhoneApplicationPage
{
    Button AddButton

    public MainPage()
    {
        CreateInterestEntry();
    }

    private void CreateInterestEntry()
    {
        EntrySegment = getEntrySegment();
        ContentPanel.Children.Add(EntrySegment);
    }

    private void AddButton_Click(Object sender, RoutedEventArgs e)
    {
        //Stuff to do when button is clicked
    }

    private Grid getEntrySegment()
    {
        Grid EntrySegment = new Grid();

       //Creating the grid goes here

        AddButton = new Button();
        AddButton.Content = "Add";
        AddButton.Click += new EventHandler(AddButton_Click);

        return EntrySegment;
    }
}

}

With this code it complains that no overload for AddButton_Click matches delegate "System.EventHandler".

It's virtually identical to the code under Examples here at msdn, with the exception I've changed the argument type in AddButton_Click from EventArgs to RoutedEventArgs as otherwise Visual Studio tells me that it cannot implicitly convert from System.EventHandler to System.RoutedEventHandler.

Thanks in advance

like image 639
user1364926 Avatar asked Dec 06 '25 03:12

user1364926


1 Answers

Try this:

AddButton.Click += new RoutedEventHandler(AddButton_Click);

And the Click Event Handler:

void AddButton_Click(object sender, RoutedEventArgs e)
{
}
like image 165
Rajeev Nair Avatar answered Dec 09 '25 19:12

Rajeev Nair



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!