简体   繁体   English

ASP.NET:在文本框中输入非数字值时会产生错误消息?

[英]ASP.NET: produce an error message when a non-numeric value is entered in a textbox?

If a user enters a non-numeric value into a TextBox and presses a Button, I want to show an error message on a Label. 如果用户在TextBox中输入非数字值并按下Button,我想在Label上显示错误消息。

How can I achieve this? 我该如何实现?

If you're working with ASP.NET webforms, perhaps you have some markup like this: 如果您使用的是ASP.NET Web表单,则可能会有这样的标记:

<asp:TextBox runat="server" ID="TextBox1" Text="Default Text!" />
<asp:Button ID="Button1" runat="server" Text="Click Me" OnClick="ChangeIt" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="default!" />

Then your code-behind will need a method to handle the button's click event. 然后,您的后台代码将需要一种方法来处理按钮的click事件。 This will cause a post-back. 这将导致回发。

protected void ChangeIt(Object sender,EventArgs e)
{
   // ensure that the value in the textbox is numbers only.
   // there are always questions here whether you care about 
   // decimals, negative numbers, etc. Implement  it as you see fit.
   string userEnteredText = TextBox1.Text.Trim();
   long resultantNumber;

   if (!long.TryParse(userEnteredText, out resultantNumber))
   {
      Label1.Text = string.Format( "It looks like this isn't a number: '{0}'",
                    userEnteredText);
   }
}

Are you saying you want to allow numbers only? 您是说只想允许数字吗?

<asp:TextBox runat="server" ID="TextBox1" />
<asp:RegularExpressionValidator runat="server" ID="RegularExpressionValidator1" ControlToValidate="TextBox1" ErrorMessage="Digits only, please" ValidationExpression="^\d+$" />

If this will allow numbers only, but will also allow you to skip the box entirely. 如果这将仅允许数字,但也将允许您完全跳过该框。 If you want to make it required, add this: 如果要使其成为必需,请添加以下内容:

<asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1" ControlToValidate="TextBox1" ErrorMessage="Required" />

Update: If you would like to accept decimal values like "3.5" in addition to just "3", modify the ValidationExpression in the RegularExpressionValidator I supplied above to read "^\\d+(\\.\\d+)?$" 更新:如果除了“ 3”之外,您还希望接受诸如“ 3.5”之类的十进制值,请在上面提供的RegularExpressionValidator中修改ValidationExpression以读取“ ^ \\ d +(\\。\\ d +)?$”

Assuming you want to check whether the input is a number or a string (and display an error if the input is a string), you could do something like this using the int.TryParse function: 假设您要检查输入是数字还是字符串(如果输入是字符串,则显示错误),可以使用int.TryParse函数执行以下操作:

protected void Button1_Click(object sender, EventArgs e)
{
    int readValue;
    if (!int.TryParse(TextBox1.Text, out readValue))
        Label1.Text = "Error";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM