androidrill
androidrill

Reputation: 99

Break Down A Loop Based Solution In An Event

I have generated a set of reference numbers using nested loops and have displayed them in a combobox following a button click but now i want each one of these numbers to be displayed sequentially in a textbox on every button click. My ultimate motive is to generate a unique ID on each button click.

    char ch, sh;
    int i;
    private void button1_Click(object sender, EventArgs e)
    {
        for (sh = 'A'; sh <= 'Z'; sh++)
        {
            for (ch = 'a'; ch <= 'z'; ch++)
            {
                for (i = 1; i <= 9; i++)
                {
                    comboBox1.Items.Add(i + ch.ToString()+sh.ToString());
                }

            }
        }
    }

Upvotes: 0

Views: 60

Answers (1)

Servy
Servy

Reputation: 203828

So first we can create an iterator block to generate a sequence of values based on your current definition:

//TODO: rename method to something meaningful
public static IEnumerable<string> GenerateStrings()
{
    for (char sh = 'A'; sh <= 'Z'; sh++)
        for (char ch = 'a'; ch <= 'z'; ch++)
            for (int i = 1; i <= 9; i++)
                yield return string.Concat(i, ch, sh);
}

Then we can create an instance of this sequence as an instance field and get the next item each time the button is clicked:

private IEnumerator<string> stringSequence = GenerateStrings().GetEnumerator();
private void button1_Click(object sender, EventArgs e)
{
    if (stringSequence.MoveNext())
        textbox.Text = stringSequence.Current;
}

On a side note, normally one would want to dispose of IEnumerator<T> objects when done with them. While you certainly could dispose of this object within the form's Dispose method, in this particular case there isn't anything for the enumerator to clean up, so it's not necessary, just be wary since many enumerators do need to be disposed.

Upvotes: 2

Related Questions