![](/img/trans.png)
[英]How to know the data type of value entered by user at runtime in textbox?
[英]How to restrict user to TextBox if value entered is incorrect
在我的程序中,我有一個TextBox
,其值必須設置在特定的整數范圍內。 如果它不在此范圍內,則應警告用戶,然后突出顯示TextBox
內部的錯誤文本以進行重新編輯(暗示用戶必須輸入一個在正確范圍內的值才允許他們離開TextBox
)。 我如何更改代碼以便執行這些操作?
這就是我到目前為止所擁有的。 我正在使用TextChanged
事件。 此代碼警告用戶有關限制違規和重新聚焦(我想在TextBox
突出顯示該值),但不會阻止用戶隨后點擊它:
int maxRevSpeed;
//Max Rev Speed -- Text Changed
private void maxRevSpeed_textChanged(object sender, RoutedEventArgs e)
{
if (maxRevSpeed_textBox.Text == "" || maxRevSpeed_textBox.Text == " ")
maxRevSpeed = 0;
else
{
maxRevSpeed = Convert.ToInt32(maxRevSpeed_textBox.Text);
if (maxRevSpeed <= 0 || maxRevSpeed > 45)
{
MessageBox.Show("Reverse Sensor speed must be between 0 and 45 FPM", "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
}
maxRevSpeed_textBox.Focus();
}
}
請注意,這個問題是對我前一個問題的重新審視。 我知道將這種方法用於TextBox
可能會“不贊成”,但不管我還是想知道如何實現這樣的東西。 謝謝。
更新1:
在查看每個人的建議后,我更新了我的代碼:
//Max Rev Speed -- Text Changed
private void maxRevSpeed_textChanged(object sender, RoutedEventArgs e)
{
if (maxRevSpeed_textBox.Text == "" || maxRevSpeed_textBox.Text == " ") //Is Empty or contains spaces
maxRevSpeed = 0;
else if (!Regex.IsMatch(maxRevSpeed_textBox.Text, @"^[\p{N}]+$")) //Contains characters
maxRevSpeed = 0;
else
maxRevSpeed = Convert.ToInt32(maxRevSpeed_textBox.Text);
}
//Max Rev Speed -- Lost Focus
private void maxRevSpeed_LostFocus(object sender, RoutedEventArgs e)
{
if (maxRevSpeed <= 0 || maxRevSpeed > 45)
{
MessageBox.Show("Reverse Sensor speed must be between 0 and 45 FPM", "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
//Supposed to highlight incorrect text -- DOES NOT WORK
maxRevSpeed_textBox.SelectionStart = 0;
maxRevSpeed_textBox.SelectionLength = maxRevSpeed_textBox.Text.Length;
}
}
表示textBox
本的integer
現在在textChanged
事件中處理。 LostFocus
事件處理警告並重新選擇不正確的文本值。 但是,高亮顯示文本方法在textChanged
事件中有效,但在當前位置時無效。 為什么會這樣,我該如何解決?
您可以使用文本框的PreviewTextInput處理程序阻止用戶輸入文本或超出范圍,像這樣調用它。
private void textBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (!char.IsDigit(e.Text, e.Text.Length - 1))
{
e.Handled = true;
}
}
上面的代碼僅用於輸入數字,您可以根據您的要求進行更改,希望它有幫助:)
如果你只是想從離開停止焦點TextBox
,所有你需要做的是設置Handled
的財產KeyboardFocusChangedEventArgs
反對true
的PreviewLostKeyboardFocus
處理程序時您的無效條件為真:
private void PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
e.Handled = IsInvalidValue;
}
這當然假設您有一個名為IsInvalidValue
的屬性,當輸入的數據無效時,您將其設置為true
,否則為false
。
嗨,我想您正在使用C#,在這里您可以找到相關的帖子: C#自動突出顯示文本框控件中的文本
正如他們所說,以下代碼應該選擇texbox中的文本
在Windows窗體和WPF中:
maxRevSpeed_textBox.SelectionStart = 0; maxRevSpeed_textBox.SelectionLength = textbox.Text.Length;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.