如何设置文本框仅接受C#Windows窗体中的十六进制值 [英] How Do I Set A Textbox Only Accept Hexadecimal Values In C# Windows Form

查看:160
本文介绍了如何设置文本框仅接受C#Windows窗体中的十六进制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在上面的问题中请帮我解决这个问题

i ma struc in this above question please help me out this

推荐答案

一种简单的方法是使用 Control.Validating Event(System.Windows.Forms) [ ^ ]。在此事件中,检查是否仅存在十六进制值中允许的字符。如果包含任何额外的字符,请将e.Cancel设置为true。



类似于:

One simple way is to use Control.Validating Event (System.Windows.Forms)[^]. In this event check that only characters allowed in hex values are present. If any extra characters are included, set e.Cancel to true.

Something like:
private void textBox1_Validating(object sender, CancelEventArgs e)
      {
         char[] allowedChars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

         foreach (char character in textBox1.Text.ToUpper().ToArray())
         {
            if (!allowedChars.Contains(character))
            {
               System.Windows.Forms.MessageBox.Show(string.Format("'{0}' is not a hexadecimal character", character));
               e.Cancel = true;
            }
         }
      }


有几种方法:但最简单的方法是处理KeyPressed事件并限制输入到0-9,AF,af:

There are several ways: but the easiest if to handle the KeyPressed event and limit the input to just 0-9, A-F, a-f:
char c = e.KeyChar;
if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')))
   {
   e.Handled = true;
   }


数字输入最好由专门为该用途设计的控件处理。当然可以修改TextBox以接受一组特定的字符,但要正确完成,你必须处理打字,粘贴和可能拖放的数据。



为什么当Microsoft提供System.Windows.Forms.NumericUpDown控件时,麻烦。



例如,使NumericUpDown只接受0x20到0xFF范围内的十六进制值

1)将十六进制设置为真

2)将最小值设置为0x20

3)将最大值设置为0xFF



就是这样。



Alan。
Numeric input is best handled by a control designed specifically for that use. Sure a TextBox could be modified to accept a specific set of characters but to do it properly you would have to handle typed, pasted and possibly drag-dropped data.

Why bother when Microsoft provide the System.Windows.Forms.NumericUpDown control.

For example to make a NumericUpDown accept only hexadecimal values in the range 0x20 to 0xFF
1) Set Hexadecimal to true
2) Set Minimum to 0x20
3) Set Maximum to 0xFF

That's it.

Alan.


这篇关于如何设置文本框仅接受C#Windows窗体中的十六进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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