简体   繁体   English

验证WinForms文本框(在C#中)

[英]Validating WinForms TextBox (in C#)

In TextBox_Leave event i need to check whether numbers entered in textbox is in serial number or not.If it is not in order then i need to display a message as "number" is missing 在TextBox_Leave事件中,我需要检查在文本框中输入的数字是否为序列号。如果不是按顺序排列,则我需要显示一条消息,因为缺少“数字”

For example : 例如 :

In textbox i have entered 3 and click tab : I need to display message as "Number is not in order , number "1" and "2" is missing " 在文本框中,我输入了3,然后单击选项卡:我需要显示消息,因为“数字顺序不正确,数字“ 1”和“ 2”缺失”

I don't know whether this also works in c#2.0, this is my experience in c#3.0: 我不知道这是否也适用于c#2.0,这是我在c#3.0中的经验:

Why do you use TextBox_Leave for that? 为什么要使用TextBox_Leave? The Validating-event should be used for validating whether input is correct. 验证事件应用于验证输入是否正确。

Combine using the Validating-event with using an ErrorProvider (you can just drag it from the toolbox onto the form) to set an error message: it will be displayed as a (blinking) exclamation mark in a red triangle. 结合使用Validating-event和ErrorProvider(您可以将其从工具箱拖到表单上)来设置错误消息:它将以红色三角形(闪烁)显示为感叹号。

An ErrorProvider can also block any submit-actions. ErrorProvider也可以阻止任何提交动作。

One trick is to retain focus in the textbox when trying to leave (with TAB for instance) in case of some condition (missing number): 一种技巧是在某些情况(缺少数字)的情况下尝试离开(例如,使用TAB)时在文本框中保留焦点:

 private void textBox1_Leave(object sender, EventArgs e)
    {
        TextBox tb = (TextBox)sender;

        if (tb.Text == "3")
            tb.Focus();
    }

Assuming you are using a standard textbox. 假设您使用的是标准文本框。 You could also use third party controls that where you can cancel an event (e.Cancel = true) on some condition. 您还可以使用第三方控件,在某些情况下可以在其中取消事件(例如,Cancel = true)。

尝试使用Masked TextBox控件并为这种类型的字段验证设置自定义属性。

Alternatively you can also use Validating event of the text box. 或者,您也可以使用文本框的Validating事件。

  private void textBox1_Validating( object sender, CancelEventArgs e )
  {
      if ( textBox1.Text == "3" )
          e.Cancel = true;
  }

The text-box wont loose focus until it receives a valid input. 文本框在收到有效输入之前不会失去焦点。

I will show you how to validate Validating WinForms TextBox (in C#). 我将向您展示如何验证Validating WinForms TextBox (在C#中)。

  1. Create a function: 创建一个函数:

     public static void ChkBlankTextBoxes(object sender, string type) { if (sender is TextBox) { TextBox textbox = sender as TextBox; if (string.IsNullOrEmpty(textbox.Text)) { MessageBox.Show("Please enter correct value value.."); textbox.Focus(); } } } 
  2. Call to created function: 调用创建的函数:

     ChkBlankTextBoxes(txt_userID, textBoxtype); ChkBlankTextBoxes(txt_password, textBoxtype); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM