0

Basically I have a string array with a few text values in it. I want to on load assign a value from the array to a string then on button press change it to the next value, once it gets to the end it needs to loop around. So the string will be set to one value in the array then get changed after a button click.

        Array stringArray = Array.CreateInstance(typeof(String), 3);
        stringArray.SetValue("ssstring", 0);
        stringArray.SetValue("sstring", 1);
        stringArray.SetValue("string", 2);
1
  • You could post what you have so far Commented May 26, 2011 at 14:46

3 Answers 3

1

Here's some code to get you going. You dont mention what environment you're using (ASP.NET, Winforms etc..)

When you provide more info I'll update my example so its more relevant.

public class AClass
{
    private int index = 0;
    private string[] values = new string[] { "a", "b", "c" };

    public void Load()
    {
        string currentValue = this.values[this.index];
    }

    private void Increment()
    {
        this.index++;

        if (this.index > this.values.Length - 1)
            this.index = 0;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Increment();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Set Index = 0

Let Count = StringArray.Count

On Button Click Do the following

Set Return Value As StringArray(Index)
Set Index =  ( Index + 1 ) Mod Count

You can program that algorithm in C#...

Comments

0

You could have a class that holds and iterates your strings like:

class StringIterator
{
    private int _index = 0;
    private string[] _strings;        

    public StringIterator(string[] strings) 
    {
        _string = strings;
    }

    public string GetString()
    {
        string result = _string[_index];
        _index = (_index + 1) % _strings.Length;
        return result;
    }
}

The usage would look like

class Program
{
    private string _theStringYouWantToSet;
    private StringIterator _stringIter;

    public Program()
    {
        string[] stringsToLoad = { "a", "b", "c" };
        _stringIter = new StringIterator(stringsToLoad);
        _theStringYouWantToSet = _stringIter.GetString();
    }        

    protected void ButtonClickHandler(object sender, EventArgs e)
    {
        _theStringYouWantToSet = _stringIter.GetString();
    }

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.