grubicon
grubicon

Reputation: 25

Changing text of buttons to sequential number 0-9

Writing some code to mimic a pin pad, but ultimately the numbers on the pad should be randomly positioned.

So i have 10 buttons on a form within a panel, and I'm looking to just have them numbered 0-9 to begin with, i currently have the following code, but it seems to start at 1, then go up in 3s

the code i currently have for this is

protected void Page_Load(object sender, EventArgs e)
{            
    int i = 0;

    foreach (var item in panel1.Controls)
    {
        if (item is Button)
        {
            var tmp = (Button)panel1.Controls[i];
            tmp.Text = i.ToString();
        }
        i++;
    }
}

The outcome looks like

Buttons 1 3 5 .. 19

I cannot understand why it isn't starting at 0 and going up to 9.

Upvotes: 2

Views: 118

Answers (2)

John Saunders
John Saunders

Reputation: 161773

if (item is Button)
{
    ((Button)item).Text = i.ToString();
    i++;
}

You already have the button. You don't need to index. Also, i now counts only buttons.

Upvotes: 3

chouaib
chouaib

Reputation: 2817

your i counts all controls, you need another var to count only Buttons :

int j=0;
foreach (var item in panel1.Controls)
        {
            if (item is Button)
            {
                var tmp = (Button)panel1.Controls[i];
                tmp.Text = j.ToString();
                j++;
            }
            i++;
        }

Or why won't you try directly:

if (item is Button)
{
    item.Text = j.ToString();
    j++;
}

Upvotes: -1

Related Questions