Karl
Karl

Reputation: 75

How to add one value of an array to a string

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);

Upvotes: 0

Views: 5023

Answers (3)

FlyingStreudel
FlyingStreudel

Reputation: 4464

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();
    }

}

Upvotes: 0

Martyn
Martyn

Reputation: 1476

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();
    }
}

Upvotes: 1

Viv
Viv

Reputation: 2595

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#...

Upvotes: 0

Related Questions