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 一个空字符串。