Numeric TextBox

2020-01-29 13:51发布

Im new to programming and I dont know very much about but I'm making a calculator, and i want to use a textbox that only acepts numbers and decimals, and when the user paste text from the clipboard the textbox deletes any literal characters, like the MS calc.

Please take the time to explain each part so I can learn or write it and tell me what to search.

Thanks

EDIT: I'll make it more specific:

How can I make a numeric textbox in C#? I've used the masked textbox but it wont take decimals.

I've read things about overloading the OnKeyPress method so it will correct any wrong characters but I dont know to do it.

13条回答
虎瘦雄心在
2楼-- · 2020-01-29 14:06
        if ("1234567890".IndexOf(e.KeyChar.ToString()) > 0)
        {
            e.Handled = false;
        }
        else
        {
            e.Handled = true;
        }
查看更多
霸刀☆藐视天下
3楼-- · 2020-01-29 14:09

If you look closely, In Windows Calculator, the numbers are shown in a label not a textbox (It does not receive focus). The window receives keyboard events.

So look at KeyPressed and KeyDown events on the form.

查看更多
男人必须洒脱
4楼-- · 2020-01-29 14:09

Research the MaskedTextBox.

The question is a little broad to explain everything. Try to focus the question if you want specifics because you're asking for a lot of the community to "explain each part." If you ask a few specific questions (and exclude the "please the the time to explain..."), you'll get better responses.

查看更多
贪生不怕死
5楼-- · 2020-01-29 14:11

Being a novice you might be better off investing in a good third party toolkit. Radcontrols from Telerik for instance has a numeric textbox that will accomplish what you are looking for.

查看更多
Rolldiameter
6楼-- · 2020-01-29 14:16

The easiest way :)

on Keypress event on your textbox


if ((e.KeyChar <= 57 && e.KeyChar >= 48) || e.KeyChar == 13 || e.KeyChar == 8)
{
}
else
{
     e.Handled = true;
}

查看更多
beautiful°
7楼-- · 2020-01-29 14:18

i would probably use a regular expression to screen out non-numerics.

pseudo code:

for (each item in the input string) {
   if (!match(some regular expression, item)) {
        toss it out
   } else {
        add item to text box or whatever you were going to do with it
   }

}
查看更多
登录 后发表回答