如何在TextBoxes数组中使用KeyPress事件 [英] How to Use KeyPress Event in Array of TextBoxes

查看:94
本文介绍了如何在TextBoxes数组中使用KeyPress事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表单中有一系列文本框。数组中有10个文本框,我想在按键上验证每个文本框,如果我这样做将是非常冗长所以我想通过文本框的数组使用krypress我试过这个代码你可以告诉我锄我应该使用它带有一组文本框



i have a array of textboxes in a form. the array has 10 textboxes in it and i want to validate each textbox on key press it will be very lengthy if i do that so i want to use the krypress through array of textbox i have tries this code can u tell me hoe i should use it with array of textboxes

Dim TxtFrom() As TextBox = {txtfr1, txtfr2, txtfr3, txtfr4, txtfr5, txtfr6, txtfr7, txtfr8, txtfr9}

        Dim TxtTo() As TextBox = {txtTo1, txtTo2, txtTo3, txtTo4, txtTo5, txtTo6, txtTo7, txtTo8, txtTo9}
  Private Sub txtfr1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtfr1.KeyPress
        e.Handled = Not (Char.IsDigit(e.KeyChar) Or e.KeyChar = ".")
    End Sub

推荐答案

在文本框数组中创建一个循环;在这个循环中,为每个人添加一个事件处理程序;在事件处理程序中,使用相同的方法处理发件人,这将是对特定文本框的引用。



如果这只是验证,是一些您甚至不需要知道对每个文本框的引用的情况都会传递给事件处理方法。但是,通常需要这样做。您可以使用的唯一信息是对发件人的引用,作为事件处理程序的第一个参数传递。



首先,您始终可以键入此引用 TextBox ,因为在这种情况下,这始终是发件人。因此,您将获得对 TextBox 的实例的引用。要传递其他信息,您可以使用属性 TextBox.Tag (继承自 Control.Tag )。在您的情况下,最好将数组中的索引分配给此标记。在事件处理程序中,键入标记 int ,这样就知道正在处理的数组元素的索引。







我差点忘了,VB.NET没有''+ = ''运算符,用于将处理程序添加到事件实例的调用列表中。您需要使用 AddHandler 。这在代码示例中显示,请参阅答案#0:

http://stackoverflow.com/questions/4199370/how-to-create-event-for-dynamic-control-array-in-vb-net [ ^ ]。



-SA
Make a loop in the array of text boxes; in this loop, add an event handler to every one; in the event handler, use the same method to deal with the sender, which will be a reference to a particular text box.

If this is just validation, is some cases you won''t even need to know a reference to each of the text boxes is passed to the event handling method. However, usually this is needed. The only information you can use is the reference to the sender, passed as a first parameter of the event handler.

First, you can always type-case this reference to TextBox, because, in this scenario, this is always the sender. So, you get a reference to an instance of the TextBox. To pass additional information, you can use the property TextBox.Tag (inherited from Control.Tag). In your case, it would be the best to assign an index in your array to this Tag. In the event handler, you type-cast Tag to int and this way know the index of the array element being handled.



I almost forgot, VB.NET does not have ''+='' operator for adding a handler to an invocation list of an event instance. You need to use AddHandler. This is shown in a code sample here, see the answer #0:
http://stackoverflow.com/questions/4199370/how-to-create-event-for-dynamic-control-array-in-vb-net[^].

—SA


这篇关于如何在TextBoxes数组中使用KeyPress事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆