0

I have already checked other questions here but the answers are not related to my issue. the following code allows textbox1 to only accept numbers if the physical keyboard (laptop) is pressed:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        char ch = e.KeyChar;
        if ( !char.IsDigit(ch))
        {

            e.Handled = true;
        }
    }

but this is not what I wanted (I dont use physical laptop keyboard).

ScreenShot

As shown in screenshot, I have windows form with buttons and a textbox. I designed this keyboard and it works well but I want textbox1 to only accept numbers and the ".".

There are only two lines of code inside each button (and only code in the project) which is:

private void buttonName_Click(object sender, EventArgs e)
    {    
         // each button only has this code.

         textBox1.Focus();
         SendKeys.Send(buttonName.Text);  
    }

I know how to set txtbox to accept numbers if the physical (laptop ) keys are pressed but here in this case I have control buttons in windwos form and I want to set textBox1 to only accept numbers and the ".". Please help in how to achieve this. Thank you

7
  • There's a million ways. Can you add more details? What have you tried that didn't work? You state that you've checked other options, why didn't they work for you? Commented Nov 21, 2015 at 13:02
  • @ Patrick .that options which i stated were related to physical buttons (laptop keys) but I have different case. Commented Nov 21, 2015 at 13:06
  • @ Patrick . I edited the question please check it. if you just could give me one solution out of the millions that you said ;) . Commented Nov 21, 2015 at 13:19
  • 2
    msdn.microsoft.com/en-us/library/ms229603(v=vs.110).aspx Commented Nov 21, 2015 at 13:23
  • 1
    Well, one is the one Grant stated, why even let the user type incorrect input? Just hide or disable the buttons that shouldn't be able to generate input. If your user can type on the keyboard as well, analyse the input and filter out the incorrect (or display an error text under the textbox that only numerical data is valid) Commented Nov 21, 2015 at 13:33

2 Answers 2

2

Declare a string variable at form level, use it to store the last valid text and to restore it when an invalid text is entered on the TextChanged event of your textbox.

string previousText;

public Form1()
{
    InitializeComponent();
    previousText = String.Empty;
}

private void textBox1_TextChanged(object sender, EventArgs e)
{
    int dummy, changeLenght, position;
    if (!String.IsNullOrWhiteSpace(textBox1.Text) && !int.TryParse(textBox1.Text, out dummy))
    {
        position = textBox1.SelectionStart;
        changeLenght = textBox1.TextLength - previousText.Length;
        textBox1.Text = previousText;
        textBox1.SelectionStart = position - changeLenght;
    }
    else
    {
        previousText = textBox1.Text;
    }
}

position and changeLenght are used to keep the cursor where it was before restoring the text.

In case you want to accept numbers with decimals or something bigger than 2147483647, just change dummy to double and use double.TryParse instead of int.TryParse.

private void textBox1_TextChanged(object sender, EventArgs e)
{
    int changeLenght, position;
    double dummy;
    if (!String.IsNullOrWhiteSpace(textBox1.Text) && !double.TryParse(textBox1.Text, out dummy))
    {
        ...
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

@naouf: it means that you won't be able to paste blanks.
@ Neolisk . I tried to modify this code so I can allow the textbox to accept the "." too, but I failed. can you help me please? thank you
@naouf strange... I tested it and never threw errors... what did you tried or input to get the error? That line is to check if what was entered into the textbox can be converted to a number or is an empty string (this is to allow the user to clear the textbox). At the end of the answer I also mentioned what you need to change to allow decimal or bigger numbers. I editet the answer to show it.
@ Josh Part. I am sorry I mixed up the code I deleted my comment. your code works very good. but one more last thing please: I just want to allow the textbox to accept the "." ( it should be only one "." in the textbox because it is not valid to have number like 54.45.63 which has 2 dots. How can I do that. Thank you very much
@naouf the second code block shows the changes needed to accept numbers with a dot (".")
|
1

Suppose button1 is your button control, you could do this:

private void allButtons_Click(object sender, EventArgs e)
{  
    Button btn = sender as Button;
    char c = btn.Text[0]; //assuming all buttons have exactly 1 character
    if(Char.IsDigit(c) || c == '.')
    {
        //process
        textBox1.Focus();
        SendKeys.Send(btn.Text);
    }
    //otherwise don't
}

I'm assuming you put this in a common handler, to which you already wired all your buttons (i.e. allButtons_Click).

Problem with this approach, it allows you to type values like 0.0.1, which are most likely invalid in your context. Another way to handle this is to process TextChanged event, store previous value, and if new value is invalid, restore the old one. Unfortunately, TextBox class does not have TextChanging event, which could be a cleaner option.

The benefit of you determining the invalid value is modularity. For example, if you later decide your user can enter any value, but only numbers can pass validation, you could move your check from TextChanged to Validate button click or similar.

Why users may want that - suppose one of the options for input is copy/paste - they want to paste invalid data and edit it to become valid, for example abc123.5. If you limit them at the entry, this value will not be there at all, so they now need to manually paste into Notepad, cut out in the invalid characters, and paste again, which goes against productivity.

Generally, before implementing any user interface limitation, read "I won't allow my user to...", think well, whether it's justified enough. More often than not, you don't need to limit the user, even for the good purpose of keeping your DB valid etc. If possible, never put a concrete wall in front of them, you just need to guide them correctly through your workflow. You want users on your side, not against you.

2 Comments

@ Neolisk . Thank you for your explanations Neolisk. I tried your code and it worked well but the problem as you said: I still can past invalid value (like "abc3"). any idea how to restore the previous value in case the pasted value is invalid? thank you
@naouf: Looks like you already have an answer from @JoshPart. Between his and mine you should have a good understanding of how it should work. Don't forget to accept one, and upvote both answers.

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.