public partial class NumberBox : MaskedTextBox
{
public NumberBox()
{
this.TextAlign = HorizontalAlignment.Right;
this.Mask = "#####.##";
this.PromptChar = ' ';
this.KeyPress += NumberBox_KeyPress;
this.KeyDown += NumberBox_KeyDown;
}
void NumberBox_KeyDown(object sender, KeyEventArgs e)
{
MaskedTextBox SenderTextBox = (MaskedTextBox)sender;
if (e.KeyCode == Keys.Enter)
{
String NumberBoxMask = SenderTextBox.Mask;
String NumberBoxText = SenderTextBox.Text;
Int32 DecimalPointLocation = NumberBoxMask.IndexOf('.');
Int32 IntegerLength = StrLeft(NumberBoxMask, DecimalPointLocation).Length;
Int32 DecimalLength = StrRight(NumberBoxMask, NumberBoxMask.Length - (DecimalPointLocation + 1)).Length;
Double aDoubleNum = 0.00;
String strInteger = NumberBoxText.Substring(0, IntegerLength);
String strDecimal = "".PadRight(DecimalLength, '0');
for (int mi = DecimalLength; mi > 0; mi--)
{
try
{
strDecimal = NumberBoxText.Substring(NumberBoxMask.Length - DecimalLength, mi);
break;
}
catch { }
}
for (int mi = 0; mi < strInteger.Length; mi++)
{
if (strInteger[mi] == ' ')
strInteger = strInteger.Remove(mi, 1);
}
for (int mi = 0; mi < strDecimal.Length; mi++)
{
if (strDecimal[mi] == ' ')
strDecimal = strDecimal.Remove(mi, 1);
}
String FormattedNum = "";
FormattedNum = strInteger.Trim().PadLeft(IntegerLength, ' ') + "." + strDecimal.Trim().PadRight(DecimalLength, '0');
SenderTextBox.Text = FormattedNum;
try
{
aDoubleNum = Double.Parse(FormattedNum);
e.Handled = true;
}
catch
{
MessageBox.Show("Invalid Value);
e.Handled = false;
}
}
}
public void NumberBox_KeyPress(object sender, KeyPressEventArgs e)
{
/* This logic is as per suggestion from */ <a href="http:
MaskedTextBox SenderTextBox = (MaskedTextBox)sender;
if (e.KeyChar == '.')
{
Int32 PositionOfDecimalPoint = SenderTextBox.Text.IndexOf('.');
PositionOfDecimalPoint++;
SenderTextBox.SelectionStart = PositionOfDecimalPoint;
SenderTextBox.SelectionLength = 0;
e.Handled = true;
}
}
private String StrLeft(String mstr, int mlen)
{
return mstr.Substring(0, mlen);
}
private String StrRight(String mstr, int mlen)
{
return mstr.Substring((mstr.Length - mlen), mlen);
}
}