Click here to Skip to main content
15,885,188 members
Articles / Web Development / ASP.NET
Article

MAC Address Text Box and Class

Rate me:
Please Sign up or sign in to vote.
4.39/5 (9 votes)
22 Aug 20064 min read 98.4K   2.6K   44   18
This is an edit box for MAC / physical addresses, with a class handler.

Sample Image - matb.jpg

Introduction

Editable MAC address fields are necessary for anyone configuring a virtual network. Since the masked text box is primitive in VS2005, I decided to create a MAC address text box of my own. This is a text box that allows a user to input a MAC address, along with a class for handling the text box.

About the code

It is very similar to the IP TextBox article posted by mawnkay, as his efforts to creating an easy to use IP text box inspired me. All it is, is six edit boxes and five static ':' text boxes between them.

Since it seems pointless just to give out a textbox that only returns a string, I have included a class to use with the text box so you may set and save the address programmatically. The code details follow.

Developers

Using the text box

Just drag and drop the DLL from the MACTools\matb\matb\bin\release directory in to your designer toolbox in Visual Studio 2005 (I put it under the "All Windows Forms" tab) and Visual Studio will automatically add it to your list of controls. You may also add the project to your existing solution. Then, when you rebuild the solution, it will be available automatically in your toolbox at the very top (above "All Windows Forms").

Next, just use it like you would any of the standard Windows Forms controls in the design editor, by dragging it to your dialog. When you drag the control into your dialog, it will automatically make it the correct size. This box does not support resizing.

Overridden properties include:

  • Text
  • BackColor
  • ForeColor

The BackColor and ForeColor may be edited in the designer properties window to match the other controls in your dialog.

Using the MAC address class (MacAddr)

The class consists of six bytes, each representing the six boxes of the text box. All you have to do is use the Address property of the MacAddr class and the TextBox's Text property interchangeably. Example:

C#
matb macTextBox = new matb();
MacAddr macVariable = new MacAddr();

// saving what the user typed into the text box
macVariable.Address = macTextBox.Text;

// loading saved address into the text box for user to see
macTextBox.Text = macVariable.Address;

You may edit the bytes of the MAC address individually, by using the properties of each byte:

C#
macVariable.FirstByte = 0x1a;
macVariable.SecondByte = 0x2b;
macVariable.ThirdByte = 0x3c;
macVariable.FourthByte = 0x4d;
macVariable.FifthByte = 0x5e;
macVariable.SixthByte = 0x6f;

Here is a small code walkthrough on what is happening behind the scenes. Here are the private variables, each representing the respective box in the TextBox control:

C#
// The bytes of the MAC address
private byte firstByte;
private byte secondByte;
private byte thirdByte;
private byte fourthByte;
private byte fifthByte;
private byte sixthByte;

Now, the tricky part. I had to devise a way to convert a string to a byte and vice versa. The hardest part was taking two letters from the string, such as "1A", and converting that into only one byte (since logically that is what it is). Here is the property the class uses to convert between the two.

C#
/// <summary>
/// Gets or sets the string value of the entire Mac Address. 
/// Note: includes colon seperators, e.g. "1a:2b:3c:4d:5e:6f"
/// </summary>
public string Address
{     
     get
     {
          string temp;
          temp = string.Format("{0:x2}:{1:x2}:{2:x2}:{3:x2}:{4:x2}:{5:x2}", 
                               firstByte, secondByte, thirdByte, 
                               fourthByte, fifthByte, sixthByte);
          return temp;
     }     
     set
     {
          string[] temp;
          byte[] byTemp;
          char[] sep = new char[1];
          sep[0] = ':';          
          temp = value.Split(sep, 6);

          //format A-F as 10-15 decimal, FormatByte() explained later
          byTemp = FormatByte(temp);

          firstByte = byTemp[0];
          secondByte = byTemp[1];
          thirdByte = byTemp[2];
          fourthByte = byTemp[3];
          fifthByte = byTemp[4];
          sixthByte = byTemp[5];      
     }
}

The line:

C#
byTemp = FormatByte(temp);

actually does the dirty work. It takes a string array and converts it into a byte array. It isn't the best way to do it, but it works.

C#
/// <summary>
/// Converts each part of sTemp between A-F
/// and converts to decimal 10-15, respectively
/// </summary>
/// <param name="sTemp"></param>
/// <returns></returns></FONT>
private byte[] FormatByte(string[] sTemp)
{     
     byte[] sRetValue = new byte[6];
     char[] cAtoF = { 'A', 'B', 'C', 'D', 'E', 'F', 'a', 'b', 'c', 'd', 'e', 'f' };
     char[] c0to9 = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

      // iterate through each byte
     for (int i = 0; i < 6; i++)
     {
          // iterate through both cAtoF and c0to9
          for (int j = 0; j < 12; j++)
          {
               // shift ASCII numbers down to decimal
               // equivilent ( 0 (48) = 0, 1 (49) = 1 ... )
               if (j < 10)
                    sTemp[i] = new string(sTemp[i].Replace(c0to9[j], 
                              (char)((int)c0to9[j] - 48)).ToCharArray());
               // shift ASCII uppercase A-F down to hex equivilant
               // decimal value ( A (65) = 10 = 0xA )
               if( j < 6 )
                    sTemp[i] = new string(sTemp[i].Replace(cAtoF[j], 
                              (char)((int)cAtoF[j] - 55)).ToCharArray());
               // shift ASCII lowercase a-f down to hex
               // equivilant decimal value ( A (97) = 10 = 0xA )
               else
                    sTemp[i] = new string(sTemp[i].Replace(cAtoF[j], 
                              (char)((int)cAtoF[j] - 87)).ToCharArray());
          }
     }

     // go through the byte array and assign
     // it the appropriate shifted string pair
     for (int i = 0; i < 6; i++)
     {
          sRetValue[i] = (byte)(sTemp[i][0] << 4 | sTemp[i][1]);
     }

     return sRetValue;
}

That is pretty much it. Now, you have a class at your disposal if you want to save the user input of the MAC address text box.

Source code is included, so if anyone comes across a better way of doing something, or adds another section to the code, let me know, as I will be eager to make the change myself.

End-user

MAC address text box

Only allows a user to type a valid hexadecimal character, case insensitive. Note, this doesn't really do any error checking, since it only allows a user to enter a valid hexadecimal value. Automatically sets focus to next box once two hex values are typed by the user in each box. ':' and '-' also move to the next box. Pads zeros to the left when any of the five sections lose focus.

Future recommendations

May want to force every character to be uppercase when user types in the box. Also, support for data-binding might be a good idea (MacAddr.Address property, and the Text property of the TextBox control).

History

  • 16/08/2006 17:42 CST: Fixed bug regarding the Text property returning a ":::::" string on an unedited text box.
  • 10/08/2006 12:44 CST: Added the BackColor and ForeColor properties to the text box control. Included a small example of code use.
  • 07/06/2006 13:41 CST: Added the MacAddr class for handling the text box programmatically.
  • 21/05/2006 01:07 CST: Added zero-padding to edit boxes when the control loses focus.
  • 14/05/2006 17:05 CST: Fixed bug regarding missing characters when two capital letters are typed in to the box. Also added default zeros to be added on initial instance.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
SuggestionCode practice Pin
Devoney30-Jul-13 18:34
Devoney30-Jul-13 18:34 
GeneralOr use the built-in MAC Address class - System.Net.NetworkInformation.PhysicalAddress Pin
Pat Kujawa6-Jan-10 10:33
Pat Kujawa6-Jan-10 10:33 
GeneralCopy/Cut/Paste feature request. Pin
sfirouza16-Sep-06 1:14
sfirouza16-Sep-06 1:14 
GeneralIP Address Text Box Pin
Taha Elsayed12-Aug-06 22:02
Taha Elsayed12-Aug-06 22:02 
GeneralRe: IP Address Text Box Pin
sfirouza13-Aug-06 0:19
sfirouza13-Aug-06 0:19 
GeneralRe: IP Address Text Box Pin
Taha Elsayed13-Aug-06 0:49
Taha Elsayed13-Aug-06 0:49 
GeneralRe: IP Address Text Box Pin
Melon0013-Aug-06 18:00
Melon0013-Aug-06 18:00 
GeneralText.get property Pin
sfirouza12-Aug-06 0:51
sfirouza12-Aug-06 0:51 
AnswerRe: Text.get property Pin
Melon0012-Aug-06 17:16
Melon0012-Aug-06 17:16 
GeneralRe: Text.get property [modified] Pin
sfirouza13-Aug-06 0:14
sfirouza13-Aug-06 0:14 
AnswerRe: Text.get property [modified] Pin
Melon0013-Aug-06 17:58
Melon0013-Aug-06 17:58 
GeneralRe: Text.get property Pin
sfirouza13-Aug-06 22:10
sfirouza13-Aug-06 22:10 
AnswerRe: Text.get property [modified] Pin
Melon0016-Aug-06 13:17
Melon0016-Aug-06 13:17 
GeneralRe: Text.get property Pin
sfirouza16-Aug-06 20:41
sfirouza16-Aug-06 20:41 
QuestionMac Address control on VC Pin
Ankata10-Aug-06 18:27
Ankata10-Aug-06 18:27 
AnswerRe: Mac Address control on VC Pin
Melon0011-Aug-06 2:46
Melon0011-Aug-06 2:46 
GeneralRe: Mac Address control on VC Pin
Ankata14-Aug-06 4:34
Ankata14-Aug-06 4:34 
AnswerRe: Mac Address control on VC Pin
Melon0015-Aug-06 10:16
Melon0015-Aug-06 10:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.