user3169539
user3169539

Reputation: 37

Create a List of existing Buttons

l've 10 ten button on my forms ( 0 to 9) to simulate a calculator All my buttons are named like this btnCalc0,btnCalc1,btnCalc2,etc...

I want to create an array or list of these buttons to handle event but it's doesn't work because btnCalc doesnt exist(btnCalc+x).

List<Button> lstBtnCalc = new List<Button>();
for (int x = 0; x < 10; x++)
{
  lstBtnCalc.Add(btnCalc+x)); 
}

private void myClick(object sender, EventArgs e)
{
    int index = lstBtnCalc.IndexOf(sender as Button);
}

Upvotes: 0

Views: 13618

Answers (4)

David Arno
David Arno

Reputation: 43254

You could populate your array with a loop (See ASh's answer). However, in doing so, you make the code harder to read. The primary test of good code is readable code, so avoid "clever" solutions and keep it simple. In this case, a simple, easy to read and maintain, way is:

List<Button> lstBtnCalc = new List<Button>
{
    btnCalc0, btnCalc1, btnCalc2, btnCalc3, btnCalc4,
    btnCalc5, btnCalc6, btnCalc7, btnCalc8, btnCalc9
}

Upvotes: 3

n00b
n00b

Reputation: 1852

a bit fluent:

 List<Button> lstBtnCalc =   this.Controls.OfType<Button>().Where(a => a.Name.StartsWith("btnCacl")).ToList();

Upvotes: -1

jdweng
jdweng

Reputation: 34421

Try this

 public partial class Form1 : Form
    {
        List<Button> lstBtnCalc = null;
        public Form1()
        {
            InitializeComponent();

            lstBtnCalc = new List<Button>() { button1, button2, button3, button4 };


        }
    }

Upvotes: 0

Pawel Maga
Pawel Maga

Reputation: 5787

You can use Find method:

List<Button> lstBtnCalc = new List<Button>();
for (int x = 0; x < 10; x++)
{
    var buttonName = string.Format("btnCalc{0}",x);
    var button = this.Controls.Find(buttonName);

    if (button != null)
    {
        lstBtnCalc.Add(button);
    }
}

Upvotes: 0

Related Questions