我有一个TextBox
和保存按钮。 Textbox
仅设置为数字,必须输入至少3个数字和最多4个数字。我需要这样做,以便在框中输入所有或什至一个空格时,我需要显示一条错误消息。在当前代码中,我设置了输入2位数字后将显示的错误消息。但是mtuValue
是int属性。我需要一条if语句来避免并显示whitespace
。代码如下。此当前代码适用于目前设置的任何内容。因此,我需要的是whitespace
的if语句。提前非常感谢。
private ICommand MTUsavecommand_;
public ICommand MTUsavecommand
{
get
{
if (null == MTUsavecommand_)
{
MTUsavecommand_ = new RelayCommand(o =>
{
if (mtuValue < 100)
{
MtuMsg = "MTU value should be atleast 3 digits.";
MtuMsgVisibility = Visibility.Visible;
}
else
{
Mouse.OverrideCursor = Cursors.Wait;
RouteManager?.DoMTU();
Mouse.OverrideCursor = null;
MtuMsg = "MTU saved successfully. Service will be restarted.";
MtuMsgVisibility = Visibility.Visible;
}
});
}
return MTUsavecommand_;
}
}
public int mtuValue
{
get { return Configuration.MTU; }
set
{
if (Configuration.MTU != value)
{
Configuration.MTU = value;
OnPropertyChanged();
}
}
}
如果您的项目是Winforms
,则可以通过TextChanged
事件检查TextBox中的数字是否满足要求。您可以使用控件errorProvider显示错误提示。
public Form1()
{
InitializeComponent();
// Set the blinking style: The error icon has been displayed, and blinks when it is still wrong to assign a new value to the control.
errorProvider.BlinkStyle = ErrorBlinkStyle.BlinkIfDifferentError;
// Set the distance of the error icon from the control
errorProvider.SetIconPadding(this.textBox, 5);
}
private void textBox_TextChanged(object sender, EventArgs e)
{
// Use TryParse method to check the format of digit (a properly formatted number should not contain spaces)
int number;
bool success = Int32.TryParse(textBox.Text, out number);
string temp = textBox.Text.Trim();
if (success && temp.Length == textBox.Text.Length) // Check for spaces at the beginning and end
{
// Check the number of digits
if (textBox.Text.Length < 3 || textBox.Text.Length > 4)
errorProvider.SetError(this.textBox, "Please input 3 or 4 digits");
else
errorProvider.SetError(this.textBox, "");
}
else // Wrong format
{
errorProvider.SetError(this.textBox, "Please input digit in right format");
}
}