This article will show you how you can restrict user to enter
only numbers and negative number values in text using c#.net in windows
application.
Some of my previous articles are as follows: Line
Chart in Asp.Net Using C#.Net and VB.Net, Dynamically
Add textbox control on button click in windows application using C#.net and
VB.net, Paging
in DataGridview Using C#.Net In Windows Application, Show
Progressbar While Moving Folder File From One Directory To Other Using C#.Net
In Windows Application, How
to Create Column Chart in Windows Application Using C#.Net, Windows
Application - Excel Sheet Name in C#.Net, Bind
And Display Image in a DatagridView Using C#.Net in Windows Application.
So for this article first we will create a new windows
application and add the below code into keypress event of the textbox.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public
Form1()
{
InitializeComponent();
}
private
void btnadd_Click(object
sender, EventArgs e)
{
}
///
/// Validate textbox to enter only number
///
|
///
///
private
void textBox1_KeyPress(object sender, KeyPressEventArgs
e)
{
/*This
will validate all type of numbers*/
if
((!char.IsDigit(e.KeyChar)) && !char.IsControl(e.KeyChar) && (e.KeyChar != '-') && (e.KeyChar != '.'))
{
e.Handled = true;
}
/* This
will allow only allow minus sign at the beginning*/
if
(e.KeyChar == '-' && (sender as TextBox).Text.Length
> 0)
{
e.Handled = true;
}
/* This
will allow only allow one decimal point*/
if
(e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}
}
}
In above code I have first validated weather the added value
is number, negative number or decimal number or not. After they it have been
validated that user must place negative sign at first place of the number and
after that it have been validated that decimal sign added anywhere between
numbers and it must be only one time.
So we have done check the output.
Thanks...
ReplyDeleteYou most welcome.
Delete