您好我怎样才能只允许在我的文本框中输入数字并检查文本框是否为空并在两种情况下都显示消息
答案 0 :(得分:2)
对于ASP.NET,使用RegularExpressionValidator和RequiredFieldValidator控件在回发时验证输入,如此。
<asp:TextBox ID="numericTextBox" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="regularExpressionValidator" runat="server" ControlToValidate="numericTextBox" ValidationExpression="[0-9]+" ErrorMessage="Please enter a valid numeric value"></asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="requiredFieldValidator" runat="server" ControlToValidate="numericTextBox" ErrorMessage="Please enter a numeric value"></asp:RequiredFieldValidator>
对于WinForms,您可以使用NumericUpDown控件来控制数值的输入。
答案 1 :(得分:0)
这个问题有点模糊,但我想我明白你在问什么。要仅允许数字字符,您可以使用KeyPress事件
private void TextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
else
{
MessageBox.Show("Textbox must be numeric only!");
}
}
我认为您希望在某些时候验证该框以确保输入数据。为此,请使用以下内容:
private bool CheckTextBox(TextBox tb)
{
if(string.IsNullOrEmpty(tb.Text))
{
MessageBox.Show("Textbox can't be empty!");
return false;
}
return true;
}