If a user enters a non-numeric value into a TextBox and presses a Button, I want to show an error m开发者_JAVA百科essage on a Label.
How can I achieve this?
If you're working with ASP.NET webforms, perhaps you have some markup like this:
<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. 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+)?$"
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:
protected void Button1_Click(object sender, EventArgs e)
{
int readValue;
if (!int.TryParse(TextBox1.Text, out readValue))
Label1.Text = "Error";
}
精彩评论