【问题标题】:Attaching 1 validating event handler to Multiple textboxes将 1 个验证事件处理程序附加到多个文本框
【发布时间】:2017-07-20 09:37:26
【问题描述】:

概览

我在那里进行了研究,我知道有大量信息将多个事件处理程序订阅到单个事件,但是,我无法将其应用于我的场景。几乎我有大约 30 个来自 textBoxvalidation event 处理程序,它们都在执行相同的过程。以下是其中一个处理程序:

  private void txt_HouseName_Validating(object sender, CancelEventArgs e)
        { // Convert User input to TitleCase After focus is lost.

            if (Utillity.IsAllLetters(txt_HouseName.Text) | !string.IsNullOrEmpty(txt_HouseName.Text))
            {
                errorProvider.Clear();
                txt_HouseName.Text = Utillity.ToTitle(txt_HouseName.Text);
                isValid = true;
            }
            else
            {
                errorProvider.SetError(txt_HouseName, "InValid Input, please  reType!!");
                isValid = false;

                //MessageBox.Show("Not Valid");
            }

        }

如何将我的代码最小化为这些代码行之一,并且只有其中一个事件处理程序? 我知道我应该在设计器代码中附加它们类似的东西

this.txt_Fax.Validating += new System.ComponentModel.CancelEventHandler(this.txt_Fax_Validating);

但是因为它们是 textboxes 我将如何将 1 validating events handlers 附加到我所有的 TextBoxes

【问题讨论】:

    标签: c# winforms textbox event-handling


    【解决方案1】:

    您应该使用object sender 参数。因为发送者只不过是调用事件处理程序的对象。因此,有一个全局事件处理程序并将相同的处理程序附加到所有文本框。您的事件处理程序将如下所示。

    private void txt_Validating(object sender, CancelEventArgs e)
            { // Convert User input to TitleCase After focus is lost.
    
              //Cast the sender to a textbox so we do not need to use the textbox name directly
                TextBox txtBx = (TextBox)sender; 
                if (Utillity.IsAllLetters(txtBx.Text) | !string.IsNullOrEmpty(txtBx.Text))
                {
                    errorProvider.Clear();
                    txtBx.Text = Utillity.ToTitle(txtBx.Text);//using the cast TextBox
                    isValid = true;
                }
                else
                {
                    errorProvider.SetError(txtBx, "InValid Input, please  reType!!");
                    isValid = false;
    
                    //MessageBox.Show("Not Valid");
                }
    
            }
    

    由于object sender 参数几乎与每个事件一起传递,因此可以轻松地对类似事件进行通用回调,只需检查发送者并执行特定操作。

    【讨论】:

    • 另外,您可能希望将sender 改为TextBox,而不是Object,这样您的智能感知才能正常工作。基本上删除TextBox txtBx = (TextBox)sender; 并直接使用sender,但这是可选的。
    • @Luke 不能作为 EventHandler 的签名是 (object,EventArgs) 可以将 TextBox 转换为对象,因为 TextBox 继承自对象,反之则不然。建议的编辑将给出 no matching overload 错误。
    • 是吗?对我来说很好用。在 VB.NET 中一直使用它。是 VB.NET/C# 的区别还是严格的选项之一 - 更改?
    • 是的,我猜 C# 使用比 VB 更多的类型安全,如果您尝试将事件处理程序附加到 VB 中不是 TextBox 的其他控件,则会在运行时产生异常。这在 C#@Luke 中不会发生
    • 好点。不知道那件事。你赢了:-) #NoMoreChatInComments
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 2013-08-17
    相关资源
    最近更新 更多