Visual Studio - Affect all textboxes at once

我与影子孤独终老i 提交于 2019-12-25 02:08:58

问题


I am trying to remove leading zeroes from my textboxes. I have the code working, but I have close to 50 textboxes. I don't really want to have to make 50 textbox.TextChanged events.

Is there anyway to affect all of the textboxes with the same code?

This is the code I am using:

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

回答1:


First step is to define a general purpose handler

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

Then attach every one of your TextBox instances to this single handler

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

Note that if you had all of the TextBox instances in a collection this could be done with a For Each loop as well

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



回答2:


    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


来源:https://stackoverflow.com/questions/21419956/visual-studio-affect-all-textboxes-at-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!