Redeem button through id

0

Good evening, I am developing a graph, academic work ..

.. The idea is to do a "maze", so I generate the same at runtime, and I keep a "reference" of each button in a list, but I got to a point where I need to change the color of a button and came up the following question: If I know exactly what button id, how do I have a method "grab" this button so I can handle it? Here is the method that instantiates my list:

 private List<ListaVertices> CriarBotoes()
        {
        Point localizacao = new Point(0, 0);
        List<ListaVertices> lista = new List<ListaVertices>();
        int IdBtn = 0;
        int DimensaoBtn = 35;

        for (int y = 0; y < TamanhoY; y++)
        {

            Button b = new Button
            {
                Width = DimensaoBtn,
                Height = DimensaoBtn,
                Name = IdBtn.ToString(),
                Location = localizacao,

            };
            b.Text = b.Name;
            this.Controls.Add(b);
            ListaVertices ElementoY = new ListaVertices { IdVertice = IdBtn }; // adiciona novo elemento na lista.
            lista.Add(ElementoY); // adiciona novo elemento na lista.
            IdBtn++;

            localizacao.X += DimensaoBtn;

            for (int x = 0; x < TamanhoX; x++)
            {

                Button btn = new Button
                {
                    Width = DimensaoBtn,
                    Height = DimensaoBtn,
                    Name = IdBtn.ToString(),
                    Location = localizacao,
                };
                localizacao.X += DimensaoBtn;
                btn.Text = btn.Name;
                this.Controls.Add(btn);
                ListaVertices ElementoX = new ListaVertices { IdVertice = IdBtn }; // adiciona novo elemento na lista.
                lista.Add(ElementoX); // adiciona novo elemento na lista.
                IdBtn++;

            }
            localizacao.Y += DimensaoBtn;
            localizacao.X = 0;
        }

        return lista;
    }
    
asked by anonymous 25.10.2017 / 00:25

1 answer

1

Try a little Linq:

this.Controls.OfType<Button>().FirstOrDefault(c => c.Name == "idButton");

Placing in a static method, as you requested:

public static Button GetButton(Form f, string id)
{
   return f.Controls.OfType<Button>().FirstOrDefault(c => c.Name == id);
}
    
25.10.2017 / 00:29