开发者

only allow numeric chars to be entered in text-box in c# [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

C# Numeric Only TextBox Control

开发者_如何学Python

Hi how can i allow only numbers to be entered in my text-box and to check if the text-box is empty and display a message in both situations


For ASP.NET use the RegularExpressionValidator and the RequiredFieldValidator controls to validate the input upon postback like so.

<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>

For WinForms you can make use of the NumericUpDown control to constain input to numeric values.


This question is a bit vague but I think I understand what you are asking. To only allow numeric characters you can use the KeyPress event

private void TextBox_KeyPress(object sender, KeyPressEventArgs e)
{
  if (Char.IsDigit(e.KeyChar))
  {
    e.Handled = true;
  }
  else
  {
     MessageBox.Show("Textbox must be numeric only!");
  }
}

I presume you want to validate the box at some point to make sure data has been entered. To do that use something like:

private bool CheckTextBox(TextBox tb)
{
   if(string.IsNullOrEmpty(tb.Text))
   {
     MessageBox.Show("Textbox can't be empty!");
     return false;
   }

   return true;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜