Rescue button through id

Asked

Viewed 41 times

0

Good night, I’m developing a graph, academic work..

.. The idea is to make a "maze", so I go 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 the following question arose: if I know exactly what the button id is, How do I get a method to "grab" this button so I can manipulate it? Follow 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;
    }

1 answer

1


Try a little Linq:

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

Placing in a static method, as requested:

public static Button GetButton(Form f, string id)
{
   return f.Controls.OfType<Button>().FirstOrDefault(c => c.Name == id);
}
  • And if I wanted to access through a class other than Form, it’s possible?

  • then you would have to pass the form as parameter... and in place of this the object of the form. Anything puts an example of how it would be to see better

  • this. Controls is my form? I have a Static class that are with my methods, just by organization

  • in case that command is inside your form, the this is the form itself. in a static method, this does not work. But, just put the form as parameter

  • I changed the answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.