- 1 year ago
How to I condition a text box for a string if it holds a integer
Comment
1 / 1
To condition a text box to accept only integers, you can use the KeyPress
event in a Windows Forms application. The following steps demonstrate how to achieve this in C#:
Open your Windows Forms application in Visual Studio.
Add a TextBox control to your form.
Subscribe to the
KeyPress
event of the TextBox.In the event handler, check if the entered character is a digit or a control character (e.g., backspace). If it is not a digit, cancel the event to prevent the character from being entered.
Here's a sample code snippet to illustrate the steps:
csharpusing System;
using System.Windows.Forms;
namespace WindowsFormsApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
textBox1.KeyPress += TextBox1_KeyPress;
}
private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// Check if the entered character is a digit or a control character (e.g., backspace)
if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
{
// Cancel the event to prevent the character from being entered
e.Handled = true;
}
}
}
}
Now, the TextBox will only accept numeric values, and other characters (e.g., letters, symbols) will not be allowed.