Reputation: 43
Hello everyone i made C# program and i want to make textbox only accept Number i tryed many different code and i get same errors please help this is my code
private void agetxt_Click(object sender, EventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
and this is the error message i get
Error CS1061 'EventArgs' does not contain a definition for 'KeyChar' and no extension method 'KeyChar' accepting a first argument of type 'EventArgs' could be found (are you missing a using directive or an assembly reference?) WindowsFormsApplication1 C:\Users\ziadm\Documents\Visual Studio 2015\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Form2.cs 176 Active
Upvotes: 0
Views: 4977
Reputation: 2833
You're using a Click
event which doesn't contain the KeyChar
property. You'd probably like to use the KeyPress
event on the TextBox
and implement the same logic which incorporates the KeyChar
property to be able to check if the typed character is a digit or not.
public Form1()
{
InitializeComponent();
agetxt.KeyPress += agetxt_KeyPress;
}
private void agetxt_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
Upvotes: 4