Loop through string on button click Xamarin

 private void Button_Clicked(object sender, EventArgs e)
    {

        string[] quotes = new string[3];
        quotes[0] = "1st quote";
        quotes[1] = "2nd quote";
        quotes[2] = "3rd quote";

        for (int i = 0; i < quotes.Length; i++)
        {
            label.Text = quotes[i];
        }
    }

This is my first "test" project with xamarin and I'm trying to figure out how to loop through a string on button click. Also, when a certain "quotes[i]" exists its value is equal to the label.Text in my XAML file. I'm getting confused on when I can use int vs string since this is different from JS.

2 answers

  • answered 2018-10-11 20:03 RippStudwell

    Your code will run through the entirety of your loop every time you click your button. To get what you want, set a global int and increment it after each click instead.

        private int currentIndex = 0;
        private void Button_Clicked(object sender, EventArgs e)
            {
                 string[] quotes = new string[3];
                 quotes[0] = "1st quote";
                 quotes[1] = "2nd quote";
                 quotes[2] = "3rd quote";
    
                 label.Text = quotes[currentIndex];
                 currentIndex++;
            }
    

  • answered 2018-10-12 02:39 jamesfdearborn

    The issue here is the variable is not global, so when the user stops clicking on the button their progress resets.

    private int currentIndex = 0;
    private void Button_Clicked(object sender, EventArgs e)
            {
                 string[] quotes = new string[3];
                 quotes[0] = "1st quote";
                 quotes[1] = "2nd quote";
                 quotes[2] = "3rd quote";
    
                 label.Text = quotes[currentIndex];
                 currentIndex++;
                 if (currentIndex == 3){
                    currentIndex = 0
                 }
            }
    

    This answer ensures that once the user has clicked thrice it does not crash the program like RippStudwell's answer will.