数字文本框

发布于 2024-07-13 01:51:35 字数 290 浏览 5 评论 0原文

我是编程新手,我不太了解,但我正在制作一个计算器,我想使用一个仅接受数字和小数的文本框,当用户从剪贴板粘贴文本时,文本框会删除任何文字字符,例如MS 计算

请花时间解释每个部分,以便我可以学习或编写它并告诉我要搜索什么。

谢谢

编辑:我会更具体:

How can I make a numeric textbox in C#? 我已经使用了屏蔽文本框,但它不会采用小数。

我读过有关重载 OnKeyPress 方法的内容,因此它将纠正任何错误的字符,但我不知道该怎么做。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

触ぅ动初心 2024-07-20 01:51:35

为您只想输入数字的文本框添加一个事件处理程序,并添加以下代码:

private void textBoxNumbersOnly_KeyPress(object sender, KeyPressEventArgs e)
{
   if (Char.IsDigit(e.KeyChar) || e.KeyChar == '\b')
   {
      e.Handled = false;
   }
   else
   {
      e.Handled = true;
   }
}

这允许输入数字 0 到 9,也可以使用退格键(恕我直言,很有用)。 允许通过“.” 如果你想支持小数字符

Add an event handler for the textbox you want to be numeric only, and add the following code:

private void textBoxNumbersOnly_KeyPress(object sender, KeyPressEventArgs e)
{
   if (Char.IsDigit(e.KeyChar) || e.KeyChar == '\b')
   {
      e.Handled = false;
   }
   else
   {
      e.Handled = true;
   }
}

This allows for numbers 0 to 9, and also backspaces (useful IMHO). Allow through the '.' character if you want to support decimals

我的影子我的梦 2024-07-20 01:51:35

如果仔细观察,在 Windows 计算器中,数字显示在标签中而不是文本框中(它不接收焦点)。 窗口接收键盘事件。

因此,请查看表单上的 KeyPressed 和 KeyDown 事件。

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.

失退 2024-07-20 01:51:35

最简单的方法:)

在文本框上的按键事件上


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

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;
}

油焖大侠 2024-07-20 01:51:35

框架中有一个专门用于数字输入的控件:NumericUpDown 控件。 它还管理十进制值。

There is a control in the framework which is specially made for numeric input : the NumericUpDown control. It also manages decimal values.

(り薆情海 2024-07-20 01:51:35
        if ("1234567890".IndexOf(e.KeyChar.ToString()) > 0)
        {
            e.Handled = false;
        }
        else
        {
            e.Handled = true;
        }
        if ("1234567890".IndexOf(e.KeyChar.ToString()) > 0)
        {
            e.Handled = false;
        }
        else
        {
            e.Handled = true;
        }
完美的未来在梦里 2024-07-20 01:51:35

研究 MaskedTextBox。

这个问题有点宽泛,无法解释一切。 如果您想要具体细节,请尝试集中问题,因为您要求社区中的很多人“解释每个部分”。 如果您提出一些具体问题(并排除“请花时间解释一下……”),您会得到更好的答复。

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.

郁金香雨 2024-07-20 01:51:35

据我所知,.NET 框架(至少是 2.0)本身没有任何东西可以做到这一点。 您的选择是:

  1. 创建一个自定义控件
    继承自文本框控件
    并且只允许数字输入。 这
    其优点是可以控制
    可以重复使用。
  2. 处理
    KeyPress 事件并检查
    charCode 只允许数字
    击键。 这更容易,但也很多
    可重复使用性较差。

As far as I am aware there's nothing native in the .NET framework (2.0 at least) to do this. Your options would be:

  1. Create a custom control which
    inherits from the textbox control
    and only allows numeric input. This
    has the advantage that the control
    can be reused.
  2. Handle the
    KeyPress event and check the
    charCode to only allow numeric
    keystrokes. This is easier but much
    less reusable.
假扮的天使 2024-07-20 01:51:35

我可能会使用正则表达式来筛选非数字。

伪代码:

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
   }

}

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
   }

}
雄赳赳气昂昂 2024-07-20 01:51:35

这里如何在 vb.net 中执行此操作

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    Dim reg As New System.Text.RegularExpressions.Regex("[^0-9_ ]")
    TextBox1.Text = reg.Replace(TextBox1.Text, "")
End Sub

只需修复正则表达式以满足您的特定需求

here how to do this in vb.net

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    Dim reg As New System.Text.RegularExpressions.Regex("[^0-9_ ]")
    TextBox1.Text = reg.Replace(TextBox1.Text, "")
End Sub

just fix the regex for your specific needs

戏舞 2024-07-20 01:51:35

您可以使用纯文本框或标签作为计算器显示,并确保值(字符串?)始终是数字。 例如,您可以保留一个双精度值,并在希望显示时将其转换为字符串。

You could use a plain textbox or label as the calculator display and just make sure the value (a string?) is always a number. For instance, you could keep a double and convert it to a string when you wish to display it.

左秋 2024-07-20 01:51:35

对于十进制数字输入很有用,但如果(右键单击并粘贴)其他文本则有一些错误。 :D

 private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        string original = (sender as TextBox).Text;
        if (!char.IsDigit(e.KeyChar))
        {
            e.Handled = true;
        }
        if (e.KeyChar == '.')
        {
            if (original.Contains('.'))
                e.Handled = true;
            else if (!(original.Contains('.')))
                e.Handled = false;

        }
        else if (char.IsDigit(e.KeyChar)||e.KeyChar=='\b')
        {
            e.Handled = false;
        }

    }

useful for decimal numeric entry but has some bugs if (rightclick and paste) the other text. :D

 private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        string original = (sender as TextBox).Text;
        if (!char.IsDigit(e.KeyChar))
        {
            e.Handled = true;
        }
        if (e.KeyChar == '.')
        {
            if (original.Contains('.'))
                e.Handled = true;
            else if (!(original.Contains('.')))
                e.Handled = false;

        }
        else if (char.IsDigit(e.KeyChar)||e.KeyChar=='\b')
        {
            e.Handled = false;
        }

    }
娇女薄笑 2024-07-20 01:51:35

这是我根据 mahasen 的答案制作的自定义控件。 将其放入自己的类文件中,并将命名空间修复为您想要的任何内容。 重建解决方案后,它应该在工具箱菜单选项卡中显示为新控件,您可以将其拖放到Form上。

using System;
using System.Linq;
using System.Windows.Forms;

namespace MyApp.GUI
{
    public class FilteredTextBox : TextBox
    {
        // Fields
        private char[] m_validCharacters;
        private string m_filter;
        private event EventHandler m_maxLength;

        // Properties
        public string Filter
        {
            get
            {
                return m_filter;
            }
            set
            {
                m_filter = value;
                m_validCharacters = value.ToCharArray();
            }
        }

        // Constructor
        public FilteredTextBox()
        {
            m_filter = "";
            this.KeyPress += Validate_Char_OnKeyPress;
            this.TextChanged += Check_Text_Length_OnTextChanged;
        }

        // Event Hooks
        public event EventHandler TextBoxFull
        {
            add { m_maxLength += value; }
            remove { m_maxLength -= value; }
        }

        // Methods
        void Validate_Char_OnKeyPress(object sender, KeyPressEventArgs e)
        {
            if (m_validCharacters.Contains(e.KeyChar) || e.KeyChar == '\b')
                e.Handled = false;
            else
                e.Handled = true;
        }
        void Check_Text_Length_OnTextChanged(object sender, EventArgs e)
        {
            if (this.TextLength == this.MaxLength)
            {
                var Handle = m_maxLength;
                if (Handle != null)
                    Handle(this, EventArgs.Empty);
            }
        }
    }
}

作为奖励,我希望它在输入 3 个字符后自动切换到另一个框,因此我将框的最大长度设置为 3,并且在 Form 代码中,我挂钩了 TextBoxFull 事件并专注于旁边的盒子。 这是将 4 个过滤框链接在一起以输入 IP 地址。 前两个框的表单代码如下......

    private bool ValidateAddressChunk(string p_text)
    {
        byte AddressChunk = new byte();
        return byte.TryParse(p_text, out AddressChunk);
    }
    private void filteredTextBox1_TextBoxFull(object sender, EventArgs e)
    {
        var Filtered_Text_Box = (FilteredTextBox)sender;

        if (!ValidateAddressChunk(Filtered_Text_Box.Text))
            filteredTextBox1.Text = "255";
        else
            filteredTextBox2.Focus();
    }
    private void filteredTextBox2_TextBoxFull(object sender, EventArgs e)
    {
        var Filtered_Text_Box = (FilteredTextBox)sender;

        if (!ValidateAddressChunk(Filtered_Text_Box.Text))
            filteredTextBox2.Text = "255";
        // etc.
    }

Here's a custom control I made based off mahasen's answer. Put it in it's own class file and fix the namespace to whatever you want. Once you rebuild your solution it should show up as a new control in your Toolbox menu tab that you can drag/drop onto a Form.

using System;
using System.Linq;
using System.Windows.Forms;

namespace MyApp.GUI
{
    public class FilteredTextBox : TextBox
    {
        // Fields
        private char[] m_validCharacters;
        private string m_filter;
        private event EventHandler m_maxLength;

        // Properties
        public string Filter
        {
            get
            {
                return m_filter;
            }
            set
            {
                m_filter = value;
                m_validCharacters = value.ToCharArray();
            }
        }

        // Constructor
        public FilteredTextBox()
        {
            m_filter = "";
            this.KeyPress += Validate_Char_OnKeyPress;
            this.TextChanged += Check_Text_Length_OnTextChanged;
        }

        // Event Hooks
        public event EventHandler TextBoxFull
        {
            add { m_maxLength += value; }
            remove { m_maxLength -= value; }
        }

        // Methods
        void Validate_Char_OnKeyPress(object sender, KeyPressEventArgs e)
        {
            if (m_validCharacters.Contains(e.KeyChar) || e.KeyChar == '\b')
                e.Handled = false;
            else
                e.Handled = true;
        }
        void Check_Text_Length_OnTextChanged(object sender, EventArgs e)
        {
            if (this.TextLength == this.MaxLength)
            {
                var Handle = m_maxLength;
                if (Handle != null)
                    Handle(this, EventArgs.Empty);
            }
        }
    }
}

and just as a bonus I wanted it to auto-tab to another box after I entered 3 characters so I set the box's max length to 3 and in the Form code I hooked that TextBoxFull event and focused on the box beside it. This was to chain 4 filtered boxes together to enter an IP address. Form code for the first two boxes is below...

    private bool ValidateAddressChunk(string p_text)
    {
        byte AddressChunk = new byte();
        return byte.TryParse(p_text, out AddressChunk);
    }
    private void filteredTextBox1_TextBoxFull(object sender, EventArgs e)
    {
        var Filtered_Text_Box = (FilteredTextBox)sender;

        if (!ValidateAddressChunk(Filtered_Text_Box.Text))
            filteredTextBox1.Text = "255";
        else
            filteredTextBox2.Focus();
    }
    private void filteredTextBox2_TextBoxFull(object sender, EventArgs e)
    {
        var Filtered_Text_Box = (FilteredTextBox)sender;

        if (!ValidateAddressChunk(Filtered_Text_Box.Text))
            filteredTextBox2.Text = "255";
        // etc.
    }
枯寂 2024-07-20 01:51:35

作为新手,您最好投资一个好的第三方工具包。 例如,Telerik 的 Radcontrols 有一个数字文本框,可以完成您正在寻找的内容。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文