TextBoxBase.Clear Метод

Определение

Удаляет весь текст из элемента управления "Текстовое поле".

public:
 void Clear();
public void Clear ();
member this.Clear : unit -> unit
Public Sub Clear ()

Примеры

В следующем примере кода используется TextBoxпроизводный класс для создания обработчика TextChanged события. Код в обработчике событий ограничивает данные числами. После ввода текста в элементе управления код определяет, является ли введенный текст числом. Если текст не является числом, код очищает текст из элемента управления и MessageBox отображается , чтобы предупредить пользователя о том, что принимаются только числа. В этом примере требуется, чтобы переменная Boolean с именем flag и элемент управления textBox1 были TextBox определены за пределами этого метода. В этом примере показано, как использовать переменную флага, чтобы избежать каскадного события в событии TextChanged .

private:
   bool flag;

private:
   void MyTextChangedHandler( System::Object^ sender, System::EventArgs^ e )
   {
      Int64 val;
      // Check the flag to prevent code re-entry. 
      if ( flag == false )
      {
         // Set the flag to True to prevent re-entry of the code below.
         flag = true;
         // Determine if the text of the control is a number.
         try
         {
            // Attempt to convert to long
            val = System::Convert::ToInt64( textBox1->Text );
         }
         catch ( Exception^ ) 
         {
            // Display a message box and clear the contents if not a number.
            MessageBox::Show( "The text is not a valid number. Please re-enter" );
            // Clear the contents of the text box to allow re-entry.
            textBox1->Clear();
         }
         // Reset the flag so other TextChanged events are processed correctly.
         flag = false;
      }
   }
private bool flag;

private void MyTextChangedHandler(System.Object sender, System.EventArgs e)
{
    long val;    
    // Check the flag to prevent code re-entry. 
    if(flag == false)
    {
       // Set the flag to True to prevent re-entry of the code below.
       flag = true;
       // Determine if the text of the control is a number.
       try {
          // Attempt to convert to long
          val = System.Convert.ToInt64(textBox1.Text);
       }
       catch {
          // Display a message box and clear the contents if not a number.
          MessageBox.Show("The text is not a valid number. Please re-enter");
          // Clear the contents of the text box to allow re-entry.
          textBox1.Clear();
       }
       // Reset the flag so other TextChanged events are processed correctly.
       flag = false;
    }        
 }
Private flag As Boolean    

Private Sub MyTextChangedHandler(sender As System.Object, e As System.EventArgs)
    ' Check the flag to prevent code re-entry. 
    If flag = False Then
        ' Set the flag to True to prevent re-entry of the code below.
        flag = True
        ' Determine if the text of the control is a number.
        If IsNumeric(textBox1.Text) = False Then
            ' Display a message box and clear the contents if not a number.
            MessageBox.Show("The text is not a valid number. Please re-enter")
            ' Clear the contents of the text box to allow re-entry.
            textBox1.Clear()
        End If
        ' Reset the flag so other TextChanged events are processed correctly.
        flag = False
    End If
End Sub

Комментарии

Этот метод можно использовать для очистки содержимого элемента управления вместо назначения свойству Text пустой строки.

Применяется к

См. также раздел