0

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);
        }
    }
}
2
  • OnKeyPress is 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. Commented Oct 12, 2012 at 11:14
  • I'm aware of the existance of Masked Text-Boxes. I'm simply trying to reinvent the wheel for the sake of learning. So if you can suggest any alternative solution, it will be appreciated. Commented Oct 12, 2012 at 11:20

3 Answers 3

1

You can use:

if (!char.IsDigit(e.KeyChar) && e.KeyChar != '.')
    e.Handled = true;
base.OnKeyPress(e);

That allows digit characters or .. You can make it , if you use that to seperate decimals.


Or, you could do this:

decimal value;
e.Handled = !decimal.TryParse((sender as TextBox).Text + e.KeyChar, out value);
base.OnKeyPress(e);
Sign up to request clarification or add additional context in comments.

6 Comments

So 21.47..1.5.. is a valid number?
Thanks. With a little more modification like OnTextChanged event modifications I can finally make it work and define numbers like 21.47..1.5.. as invalid.
@Samik: Added an alternative.
Thanks so much. It's a better alternative to the one I was planning.
@Samik: Oops, I just realized that I need to add + e.KeyChar part and edited the answer.
|
1

Use the

System.Windows.Forms.NumericUpDown 

instead, it will do this for you.

3 Comments

And call what event? Or check what condition?
@Samik: It has a Decimal property called Value.
I see. But If I wanted to modify a TextBox's behaviour into accepting decimal only, how should I rewrite my algorithm?
0

You can use MaskedTextBox instead Texbox control.

Defined the Mask property on MaskedTextBox control:

maskedTextBoxInstance.Mask = "99.000";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.