Visual Studio - 立即影响所有文本框

时间:2014-01-29 00:45:03

标签: vb.net textbox visual-studio-2013

我正在尝试从文本框中删除前导零。我有代码工作,但我有近50个文本框。我真的不想参加50个textbox.TextChanged活动。

无论如何都会影响所有具有相同代码的文本框?

这是我正在使用的代码:

Private Sub txtTier1_100_TextChanged(sender As Object, e As EventArgs) Handles txtTier1_100.TextChanged

    txtTier1_100.Text = txtTier1_100.Text.TrimStart("0"c)

End Sub

2 个答案:

答案 0 :(得分:1)

第一步是定义通用处理程序

Private Sub HandleTextChanged(sender As Object, e As EventArgs) 
  Dim tb = CType(sender, TextBox)
  tb.Text = tb.Text.TrimStart("0"c)
End Sub

然后将每个TextBox个实例附加到此单个处理程序

AddHandler txtTier1_100.TextChanged, AddressOf HandleTextChanged
AddHandler txtTier1_101.TextChanged, AddressOf HandleTextChanged
AddHandler txtTier1_102.TextChanged, AddressOf HandleTextChanged

请注意,如果您拥有集合中的所有TextBox个实例,则可以使用For Each循环来完成此操作

ForEach tb in textBoxList 
  AddHandler tb.TextChanged, AddressOf HandleTextChanged
Next

答案 1 :(得分:0)

    Private Sub txtTier1_100_TextChanged(sender As Object, e As EventArgs) Handles txtTier1_100.TextChanged, txtTier1_101.TextChanged, txtTier1_102.TextChanged...

        'sender is the right textbox

    End Sub