TextBoxBase.Clear 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
將所有文字從文字方塊控制項清除。
public:
void Clear();
public void Clear ();
member this.Clear : unit -> unit
Public Sub Clear ()
範例
下列程式碼範例會使用 TextBox 衍生類別來建立事件的事件處理常式 TextChanged 。 事件處理常式內的程式碼會將資料限制為數字。 在控制項中輸入文字之後,程式碼會判斷輸入的文字是否為數字。 如果文字不是數位,程式碼會清除控制項中的文字,並 MessageBox 顯示 ,以通知使用者只接受數位。 此範例會要求 Boolean
名為 flag
的變數和 TextBox 呼叫 textBox1
的控制項定義在這個方法之外。 此範例示範如何使用旗標變數來避免事件中的 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 )
{
// 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)
{
// 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 為空字串。