如何隐藏您创建的私有void方法中的所有项目?

时间:2017-12-08 02:12:06

标签: c# button hide windows-forms-designer

所以我创建了自己的私有空间,可以创建按钮

        private void addButtonsToForm()
        {

           for (int i = 0; i < 26; i++)
         {
               Button currentNewButton = new Button();
               currentNewButton.Size = new Size(20, 30);
               currentNewButton.Location = new Point(20 + 25 * i, 420);
               currentNewButton.Text = ((char)(65 + i)).ToString();
               currentNewButton.Click += LetterClicked;
               letters[i] = currentNewButton;
               this.Controls.Add(letters[i]);
          }

        }

这些按钮是字母表,当用户想要选择一个字母时会被访问...但问题是我试图找出当用户点击或选择一个按钮时如何返回..

最初我想做的是我可以隐藏所有创建的按钮,只是让前一个按钮可见但是由于某种原因它只隐藏了点击的唯一按钮

     //this is under private void LetterClicked(object sender, EventArgs e)
      Button selectedLetter = (Button)sender;
      selectedLetter.Enabled = false;
我想到了像愚蠢的代码 addbuttonstoform().visible = false;但当然这不起作用..但你可能会想到我想去的地方....解释时有点令人困惑......我是c#中的新手,我是创造猜词游戏,所以帮助可能很棒..

1 个答案:

答案 0 :(得分:0)

这是针对您的问题的可行解决方案。见下文:

using System;
using System.Drawing;
using System.Windows.Forms;

namespace Alphabets
{
    public partial class Form1 : Form
    {
        private Button[] _letters;

        public Form1()
        {
            InitializeComponent();
            AddButtonsToForm();
        }

        private void AddButtonsToForm()
        {
            _letters = new Button[26];
            for (int i = 0; i < 26; i++)
            {
                Button currentNewButton = new Button
                {
                    Name = "BtnLetter"+ ((char)(65 + i)),
                    Size = new Size(20, 30),
                    Location = new Point(20 + 25 * i, 420),
                    Text = ((char) (65 + i)).ToString()
                };
                currentNewButton.Click += LetterClicked;
                _letters[i] = currentNewButton;
                this.Controls.Add(_letters[i]);
            }
        }

        private void LetterClicked(object sender, EventArgs e)
        {
            var selectedLetter = (Button) sender;
            //hide all other buttons
            foreach (var letter in _letters)
            {
                if (letter.Text != selectedLetter.Text)
                {
                    var buttons = this.Controls.Find("BtnLetter" + letter.Text, true);
                    buttons[0].Enabled = false;
                }
            }
        }
    }
}