Skip to content

Dynamic Button

Cycle through content with just one button.

One button is used to move through content stored in an array. The button has "Next" on it until all elements in the array have been shown. Once all the content has been shown, the button then reads "Start Over" and the content says "The End". Using a dynamic button instead of multiple buttons can make it easier to keep a large application organized.

dynamic button screenshot
dynamic button screenshot
dynamic button screenshot

Dynamic Button Code

//ProgrammingIsFun.com

 public partial class Overview : Form
    {
        public int Section = 0;
        public bool Pause = true;

        private string[] content = new string[] {
            "This example shows how to use one button to move through content in a Windows Forms application. ",
            "There is a label and a button on the form. The label is named 'content' (with a lowercase c), and the button is named 'Option'.",
            "The text shown is stored in an array named 'Content'. A variable named 'Section' is set at 0 originally, and tracks which index element is currently being shown from the array.",
            "When the button is clicked, Section is incremented and what is shown in the label is updated to the next part of the array.",
            "At the end of the array, the Section variable is set back to 0 and the text on the button is changed (to 'Start Over').",
            "This is the last element in the array. On the next button click this label will be changed to 'The End', and the button will change to say 'Start Over'."

        };

        public Overview()
        {
            InitializeComponent();
        }

        private void Option_Click(object sender, EventArgs e)
        {
            if (Option.Text == "Start Over")
            {
                Section = 0;
                Option.Text = "Next";
                UpdateContent();
            }
            else
            {
                UpdateContent();
            }
        }

        private void UpdateContent()
        {

            if (Section < content.Length)
            {
                Content.Text = content[Section];
                Pause = !Pause;
            }
            else
            {
                Content.Text = "The End";
                Option.Text = "Start Over";
                Pause = !Pause;
            }
            Section++;
            Pause = true;
        }

        private void Overview_Load(object sender, EventArgs e)
        {
            Content.Text = content[0];
        }

    }