如何能够循环生成具有相同功能的不同字母按钮?

时间:2014-02-07 06:36:32

标签: c# loops button

我目前正在做一个刽子手游戏的作业,并且必须对按钮进行编码,是否有办法能够在循环中编码所有按钮而不必逐个编码?

以下是其中一个看起来像(我正在使用Windows形式btw):

(每个按钮都是字母表中的字母,数字会更容易)

private void A_Click(object sender, EventArgs e)
{
    guess = "A";
    A.Enabled = false;
    GuessCheck();
}

1 个答案:

答案 0 :(得分:1)

这应该可以解决问题:

    private string guess = "";

    public void GuessCheck()
    {
        System.Windows.Forms.MessageBox.Show("You clicked letter " + guess);
    }


    private void Any_Click(object sender, EventArgs e)
    {
        System.Windows.Forms.Button b = (System.Windows.Forms.Button)sender;
        b.Enabled = false;
        guess = b.Text;
        GuessCheck();
    }


    private void Form1_Load(object sender, EventArgs e)
    {
        int top = 50;
        int left = 100;

        for (int i = 'A'; i <= 'Z'; ++i)
        {
            var b = new System.Windows.Forms.Button();
            b.Text = System.Convert.ToChar(i).ToString();
            b.Name = "btn" + b.Text;
            b.Left = left;
            b.Top = top;
            left += b.Width + 2;
            b.Click += Any_Click;
            this.Controls.Add(b);
        } // Next i 

    } // End Sub Form1_Load

VB.NET

Private guess As String = ""

Public Sub GuessCheck()
    System.Windows.Forms.MessageBox.Show(Convert.ToString("You clicked letter ") & guess)
End Sub ' GuessCheck


Private Sub Any_Click(sender As Object, e As EventArgs)
    Dim b As System.Windows.Forms.Button = DirectCast(sender, System.Windows.Forms.Button)
    b.Enabled = False
    guess = b.Text
    GuessCheck()
End Sub ' Any_Click


Private Sub Form1_Load(sender As Object, e As EventArgs)
    Dim top As Integer = 50
    Dim left As Integer = 100

    For i As Integer = AscW("A"c) To AscW("Z"c)
        Dim b = New System.Windows.Forms.Button()
        b.Text = System.Convert.ToChar(i).ToString()
        b.Name = "btn" + b.Text
        b.Left = left
        b.Top = top
        left += b.Width + 2
        AddHandler b.Click, AddressOf Any_Click
        Me.Controls.Add(b)
    Next i

End Sub ' Form1_Load