Home > Back-end >  Fastly rename components in c# - windows forms in visual studio 2019
Fastly rename components in c# - windows forms in visual studio 2019

Time:05-06

I am doing the table with many buttons and I am tired of manually renaming it by clicking on a button and then on the name and changing it then the same again and again. I have 81 buttons... soo I have at least 162 clicks writing the name.

Here is which clicks I need to do

CodePudding user response:

You generate the Buttons at runtime and you don't really need a known name. You can use the Tag property and a single event handler for all buttons.

for (int x=0; x < 81; x  )
{
    Button btn = new Button();
    btn.Text = x.ToString(); // Set the text you need
    btn.Tag = x.ToString();  // Set a unique tag
    btn.Click  = btOK_Click;

    MyPanel.Controls.Add(btn);
}

private void btOK_Click(object sender, EventArgs e)
{
    string tag = ((Button)sender).Tag.ToString();

    switch(Tag)
    {
        case "XXX":
           break;

        case "YYY":
           break;
    }
}

CodePudding user response:

Based on your screenshot I can assume you named all buttons but1,but2,butn 1. So you could actually use a foreach loop. Like this:

int name = 1;
foreach (Control c in myForm.Controls)
{
  if (c is Button)
  {
    ((Button)c).Name = "but"   Convert.ToString(name  );
  }
}

I haven't tested it out, but I figure it will work. Hope it helps!

  • Related