Hello community members!! I have the following question:
Is it possible to go through all the buttons in a form using any kind of iteration?

I found that i can use this:

int x = 0;
            foreach (Control control in this.Controls)
            {
                if (control is Button)
                {
                    if (control.Text == "0")
                    {
                        x += 1;

                    }
                }
            }
            label1.Text = Convert.ToString(x);

Example of application
But it's not exactly what i'm looking for. Basically i want for each label to show how many values of 0 i have in that row/column.

Example: label6 will show 0
label 7 will show 2
label 8->2
label 9->3
label 2->2
label 3->1
etc.

How can i do that?

Label 1's text is 0 because i tried to do something but it didn't work, ignore it.

Thanks for the help again :D

Recommended Answers

All 10 Replies

I just had an idea, maybe i can put buttons in a grid. Like the first row in a grid, second row in a second grid etc.. And use the foreach in that respective grid.
Could that work?
Still thinking how i could implement it though :-? Gonna come with an update if i figure more things out.

I think you would need some better issue explanation...
what kind of buttons and labels are you talking about?
Ones you want to itterate through buttons, next time you talk only about label?
Whats it gonna be?
Please try a bit better.

Did you check the image? In "Example of application".

I didnt, sorry.
I see now.
You have two axes, X and Y.
5 buttons on each. And you want to sum the number of zeros for each x ans y axes.
Am I right?

You will have to name buttons and set the correctly in order.
I suggest you to set the from the top left is button0, then you go in a row to the right (5th button in 1st two will be button4).
Last button at the buttom right will be button24.

This way you will know what to count for x and what for x axis.
I will help you a bit later with the code.
btw, Did you come up with any idea how to do it?

Pretty much yes. Though for clarification porpouses I want the final result to be like HERE

Sorry for the ambiguous text, it's kinda late here and i'm tired after a long day and my English may not be that good and coherent.

1. I see what you mean with starting from 0 to 24.

2. As i said in the other post. I had in mind to put each row and column in a grid (GroupBox i think is called) and throw a foreach for every GroupBox.
In the next example, i put the first five buttons in groupBox1 and did the following:

int x = 0;
            foreach (Control control in groupBox1.Controls)
            {
                if (control is Button)
                {
                    if (control.Text == "0")
                    {
                        x += 1;

                    }
                }
            }
            label6.Text = Convert.ToString(x);

This pretty much did, what i wanted to do. Just that i have to use it for each column and row.

Did i do it ok? Is there another way of obtaining what i wanted? I don't find my solution that much elegant to be honest.

Tried this, but didn't work:

public partial class Form1 : Form
    {
       String[,] a = new string[20,20];
       String[] v = new string[20];
       int i = 0,j=0,test;
       int eroare=0;
        public Form1()
        {
           InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
            foreach (Control control in this.Controls)
            {
                if (control is Button)
                {
                    a[i,j] = control.Text;
                    eroare += 1;
                    i += 1;
                    j += 1;
                    if (j == 3)
                    {
                        j = 0;
                    }
                    
                }
            }

            foreach (Control control in this.Controls)
            {
                if (control is Label)
                {
                    v[i] = control.Text;
                }
            }
            for (i = 0; i < 4; i++)
            {
                test = 0;
                for (j = 0; j < 4; j++)
                {

                    if (a[i, j] == Convert.ToString(0))
                    {
                        test +=1;
                    }
                    v[i] = Convert.ToString(test); 
                }

                //MessageBox.Show(Convert.ToString(test));
            }

            i = 0;

            foreach (Control control in this.Controls)
            {
                if (control is Label)
                {
                    control.Text=v[i];
                    i += 1;
                }
            }
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            
        }
    }

I think you're almost there with the second attempt but you're over-thinking things.

I think a much simpler solution would be to assign your buttons to arrays instead.

int buttonWidth = 50;
int buttonHeight = 50;

int topMargin = 300; // Distance of top of form to the button of the first row
int leftMargin = 300; // Distance of the left of form to the button of the first column

Button [,] buttonArray = new Button[5,5];

for(int columnIndex = 0; columnIndex < 5; columnIndex++)
{
    for(int rowIndex = 0; rowIndex < 5; rowIndex++)
    {
        Button newButton = new Button();
        /* Put some logic here to decide if this button has a 0 or not. If you 
         * set the 0 by clicking the button. You need to add the event here */

        // The following line sets the button "Left" position on the form.
        // 5 is added to prevent the buttons from being smack next to each other
        // But you can set this to what you want
        newButton.Left = leftMargin + (buttonWidth * columIndex) + 5;
        this.Controls.Add(newButton);
        buttonArray[rowIndex, columnIndex] = newButton;
    }
}

That would go in your form load or form constructor AFTER your InitializeComponents() method.

Checking your buttons is the same loop as above, only you use a counter to count the row and column numbers in an if statement in the middle, which checks the text content.
You would set your labels at the end of the inner loop =)

Here is the full listing, with some mistakes in it you have to fix. This will help you understand what's happening better.

public partial class Form1 : Form
    {
        int buttonWidth = 50;
        int buttonHeight = 50;

        int topMargin = 100; // Distance of top of form to the button of the first row
        int leftMargin = 100; // Distance of the left of form to the button of the first column

        const int columnLabels = 0;
        const int rowLabels = 1;

        Button[,] buttonArray = new Button[5, 5];
        Label[,] labelArray = new Label[2, 5];
        public Form1()
        {
            InitializeComponent();

            for (int axisIndex = 0; axisIndex < 2; axisIndex++)
            {
                for (int buttonIndex = 0; buttonIndex < 5; buttonIndex++)
                {
                    Label newLabel = new Label();
                    newLabel.Height = buttonHeight;
                    newLabel.Width = buttonWidth;
                    newLabel.Text = "0";
                    newLabel.TextAlign = ContentAlignment.MiddleCenter;
                    if (axisIndex == columnLabels)
                    {
                        newLabel.Left = leftMargin + (newLabel.Width * buttonIndex) + 5;
                        newLabel.Top = topMargin - (newLabel.Height + 5);
                    }
                    else
                    {
                        newLabel.Left = leftMargin - (newLabel.Width + 5);
                        newLabel.Top = topMargin + (newLabel.Height * buttonIndex) + 5;
                    }
                    
                    this.Controls.Add(newLabel);
                    labelArray[setRowLabelsOrColumnLabels?, buttonIndex] = newLabel;
                }
            }


            for (int columnIndex = 0; columnIndex < 5; columnIndex++)
            {
                for (int rowIndex = 0; rowIndex < 5; rowIndex++)
                {
                    Button newButton = new Button() { Width = buttonWidth, Height = buttonHeight };
                    newButton.Click += new EventHandler(MethodRunWhenButtonIsClicked);
                    // The following line sets the button "Left" position on the form.
                    // 5 is added to prevent the buttons from being smack next to each other
                    // But you can set this to what you want
                    newButton.Left = leftMargin + (buttonWidth * columnIndex) + 5;
                    newButton.Top = topMargin + (buttonHeight * rowIndex) + 5;
                    this.Controls.Add(newButton);
                    buttonArray[rowNumberForThisButton, columnNumberForThisButton] = newButton;
                }
            }
            this.Width = buttonArray[4, 4].Right + leftMargin + 5;
            this.Height = buttonArray[4, 4].Bottom + topMargin + 5;
        }

        void CallMeOnClick(object sender, EventArgs e)
        {
            if (!(sender is Button))
                return;

            Button currentButton = sender as TheControlType;
            currentButton.Text = currentButton.Text.Equals("0") ? String.Empty : "0";

            CheckRows();
        }

        void CheckRows()
        {
            int[] rowCount = new int[5];
            int[] columnCount = new int[5];

            for (int columnIndex = 0; columnIndex < 5; columnIndex++)
            {
                for (int rowIndex = 0; rowIndex < 5; rowIndex++)
                {
                    if (buttonArray[rowIndex, columnIndex].Text.Equals("0"))
                    {
                        // Whoops! A common mistake ;)
                        rowCount[columnIndex]++;
                        columnCount[rowIndex]++;
                    }
                    labelArray[columnLabels, columnIndex].Text = columnCount[columnIndex].ToString();
                    labelArray[rowLabels, rowIndex].Text = rowCount[rowIndex].ToString();
                }
            }

        }
    }

I hope this has helped. What you need to fix is very straightforward. I hope you've learned something from this exercise =)

commented: You are awesome! +1

Wow! Didn't know i could do those kind of things. Just shows how little i know and how much i need to learn in this field.

Can hardly wait to get home and do some more tests on it :D
Thanks!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.