Click here to Skip to main content
15,892,537 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i ma struc in this above question please help me out this
Posted

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:
C#
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;
            }
         }
      }
 
Share this answer
 
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:
C#
char c = e.KeyChar;
if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')))
   {
   e.Handled = true;
   }
 
Share this answer
 
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.
 
Share this answer
 
Have you tried this?
C#
void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    char c = e.KeyChar;
    
    if (c != '\b' && !((c <= 0x66 && c >= 61) || (c <= 0x46 && c >= 0x41) || (c >= 0x30 && c <= 0x39)))
    {
        e.Handled = true;
    }
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900