Computer Magic Logo
Programmatically add buttons with unique id

Monday, April 11, 2016

Published by Aristotelis Pitaridis

Sometimes we need to add programmatically multiple buttons with one shared button click event. At the same time we want in the click event to know the unique id of the button which has been clicked. This can be done by setting the StyleId property of the button which will host the unique id that we want to use.

public Page1 ()
{
	InitializeComponent ();

    for (int i = 0; i<10; i++)
    {
        Button CurrentButton = new Button()
        {
            Text = "Button " + (i + 1),
            StyleId = (i + 1).ToString()
        };

        CurrentButton.Clicked += MyButton_Clicked;

        MyStackLayout.Children.Add(CurrentButton);
    }
}

private void MyButton_Clicked(object sender, EventArgs e)
{
    Button ClickedButton = (Button)sender;
    ClickedButton.Text = "You clicked the button with id " + ClickedButton.StyleId;
}