I've created a custom TextBox for Windows Application using C#.NET. It must accept decimal (floated point numbers) like 8.32 and 16.002.
I've constructed the following algorithm. It is accepting pure numbers only. I can't figure out how to make it accept float as well.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace SmartTextBoxLib
{
public partial class SmartTextBox : TextBox
{
public SmartTextBox()
{
InitializeComponent();
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
base.OnKeyPress(e);
}
}
}
OnKeyPressis the wrong event to use. What if someone would paste text in your text box with the mouse? You should simply use one of the existing masked text-boxes out there.