迭代按钮及其返回值

时间:2012-10-04 14:35:32

标签: vb.net algorithm

想象一下,您有按钮,每次点击一个按钮,它都会将文本写入文本框。

即:

   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button41.Click
        textbox.Text &= "1"
    End Sub

并且假设您有10个这样的按钮作为数字(例如0-9。)而不是逐个处理这些按钮的单击事件(buttonxclickevent处理textbox.text = x);是否有更多优雅的方式来迭代这些按钮和事件?

3 个答案:

答案 0 :(得分:1)

由于您已经显示了VB.NET代码,我将回答VB.NET。你可以为所有人使用一个处理程序:

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        For Each btn In Me.Controls.OfType(Of Button)()
            AddHandler btn.Click, AddressOf buttonClicked
        Next
    End Sub

    Private Sub buttonClicked(sender As Object, e As EventArgs)
        Dim btn As Button = DirectCast(sender, Button)
        TextBox1.Text &= "1"
    End Sub

End Class

Enumerable.OfType过滤器和强制转换,结果是IEnumerable(Of Button)

答案 1 :(得分:0)

- 让该类实现ActionListener

- 像这样覆盖actionPerformed() 方法以识别按钮,并相应地在JTextField中输入消息。

JButton b1;
JButton b2;

public void actionPerformed(ActionEvent e) {
   if (e.getSource() == b1) {
      // Do something...
   }
   if (e.getSource() == b2) {
      // Do something else...
   }
}

答案 2 :(得分:0)

可以这样做:

Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) _
    Handles Button1.Click, Button2.Click, Button3.Click
        Dim b As Button = CType(sender, Button)
        Label1.Text = b.ID
End Sub