C#错误中的十进制文本框 [英] Decimal TextBox in C# error

查看:96
本文介绍了C#错误中的十进制文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨朋友

在朋友的帮助下,我们设计了一个组件:

hi friends

With the help of our friends, we designed a component:

int t=0;
protected override void OnKeyPress(KeyPressEventArgs e)
{
    string s = e.KeyChar.ToString();
    if (!(e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == '.' && t < 1 || char.IsControl(e.KeyChar)))
    {
        e.Handled = true;
    }
    if (e.KeyChar == '.') t++;
    base.OnKeyPress(e);
}


此文本框仅获取十进制数字.

问题:如果在textBox中写入,然后将其删除>> textBox不会获得."因为计数器t> 0


this text box only get decimal number.

a problem :if write in textBox and then delete it >> textBox don''t get "." because counter t >0
how can set t=0 where textBox cleared??

推荐答案

最好对TextChanged事件做出反应,并检查当前文本.
顺便说一句,对于美国设置,小数点是可以的,但并非在所有国家/地区都可以(在德国,我们使用小数点逗号)-使用CurrentUICulture.NumberFormat.NumberDecimalSeparatorCurrencyDecimalSeparator.
当然,可以通过复制/粘贴将文本添加到您的文本框中.或通过WM_SETTEXT消息,或通过某种辅助技术实现的任何方式...
Better react on the TextChanged event, and check the present text.
By the way, a decimal point is ok for US settings, but not for all countries (in Germany we use a decimal comma) - use CurrentUICulture.NumberFormat.NumberDecimalSeparator or CurrencyDecimalSeparator.
And of course text could be added to your textbox by copy/paste. Or by a WM_SETTEXT message, or whatever is implemented in some assistive technology...


解决方案1和2很好.

我想补充一点,可以使用KeyDown 事件来防止输入数字和十进制以外的内容,但同时允许使用诸如Del, BackSpace等的键.

如果需要启用仅粘贴十进制数,那么我认为WndProc 方法在此处 ^ ]将被处理.

Windows消息列表在此处给出 http://wiki.winehq.org/List_Of_Windows_Messages [
The Solution 1 and 2 are good.

I want to add that the KeyDown event can be used to prevent entry of other than numbers and decimal but at the same time allow use of keys like Del, BackSpace etc.

If it is required to enable pasting only decimal number, then I think the WndProc method explained here WndProc method[^] is to be handled.

The list of Windows Messages are given here http://wiki.winehq.org/List_Of_Windows_Messages[^]

The text to be pasted is combined with the existing text and tested with Regex with pattern "^\d*\.?\d*


"模式进行测试,以查看整个文本仅包含数字,并且不含小数或一位.

由于WndProc 是受保护的方法,因此TextBox 将被子类化以提供所需的功能,如下所示:

" before being pasted, to see that the entire text contains only digits and one or none decimal.

Since, WndProc is a protected method, the TextBox is to be sub classed to provide the desired functionality as shown below:

public class DecimalTextBox : TextBox {
    protected override void WndProc(ref System.Windows.Forms.Message m)
    {
        try {
            if (m.Msg !=0x302) {
                base.WndProc(ref m);
                return;
            }
            string modifiedText = Text + Clipboard.GetText();
            if (Regex.IsMatch(modifiedText,@"^\d*\.?\d*


这篇关于C#错误中的十进制文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆