Introduction
This is a cool code to use TextBox
for entering currency data. It will automatically add decimal when typing on the TextBox
. The backspace and delete key is used to delete a number from the TextBox
.
The source code is:
string str="";
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
int KeyCode = e.KeyValue;
if(!IsNumeric(KeyCode))
{
e.Handled=true;
return;
}
else
{
e.Handled=true;
}
if(((KeyCode==8)||(KeyCode==46))&&(str.Length>0))
{
str = str.Substring(0,str.Length-1);
}
else if(!((KeyCode==8)||(KeyCode==46)))
{
str = str+Convert.ToChar(KeyCode);
}
if(str.Length==0)
{
textBox1.Text = "";
}
if(str.Length==1)
{
textBox1.Text = "0.0"+str;
}
else if(str.Length==2)
{
textBox1.Text = "0."+str;
}
else if(str.Length>2)
{
textBox1.Text = str.Substring(0,str.Length-2)+"."+
str.Substring(str.Length-2);
}
}
private bool IsNumeric(int Val)
{
return ((Val>=48 && Val<=57) || (Val == 8) ||(Val==46));
}
private void textBox1_KeyPress(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{
e.Handled=true;
}