Share via


Visual Studio 2015: Make a NumberBox With TextBox

Preface

In this chapter we want add some properties to textbox Object.

Process

Following steps show how to create a NumberBox

  1. First, Click New Project in Start Page Or On File Menu .

  2. In New Project Dialog , Click Windows On Left Pane And Class library On Middle Pane.

  3. Choose The Project Name to your Favorite Name And Click OK.

  4. Right Click On Project And Click Add .

  5. Then Click New Item .

  6. In Add New Item . dialog , Click Windows Forms On left Pane And User Control On Middle Pane .

  7. Choose The Item Name to your Favorite Name And Click OK .

  8. Insert a TextBox On User Control .

  9. Choose TextBox Dock to Fill .

  10. Change User Control Size To TextBox Size .

  11. Now , Add This Property to Separate Numbers

    private int  num; 
    public int  SeparateNum 
    { 
    get { return num; } 
    set { num = value; } 
    } 
    
  12. And Add This Code In TextBox Key Up :    if (radTextBox1.TextLength > num)    {    int lenght = radTextBox1.TextLength;           ``var strbuild = ``new StringBuilder(``""``);           ``strbuild.Append(radTextBox1.Text);           ``string text = radTextBox1.Text;           ``for (``int k = 0; k < lenght; k++)           ``{               ``if (radTextBox1.Text.Substring(k, 1) == ``","``)               ``{                   ``strbuild.Remove(k, 1);                   ``lenght = strbuild.Length;                   ``radTextBox1.Text = strbuild.ToString();               ``}           ``}           ``radTextBox1.Text = ``""``;           ``radTextBox1.Text = strbuild.ToString();           ``lenght = strbuild.Length;           ``int div = lenght / num;           ``for (``int i = 1; i <= div; i++)           ``{               ``strbuild.Insert(lenght - num, ``","``);               ``lenght -= num;           ``}           ``radTextBox1.Text = ``""``;           ``string del;           ``del = strbuild.ToString();           ``if (del.Substring(0, 1) == ``","``)               ``strbuild.Remove(0, 1);           ``radTextBox1.Text = strbuild.ToString();           ``radTextBox1.SelectionStart = radTextBox1.TextLength;           ``radTextBox1.SelectionLength = 1;   

  13. Then Add this Code For Write Numbers Only (in Text Box KeyPress)

    if ((int)e.KeyChar == 8 || (int)e.KeyChar == 46 || (int)e.KeyChar == 48 || (int)e.KeyChar == 49 || (int)e.KeyChar == 50 || (int)e.KeyChar == 51 || (int)e.KeyChar == 52 || (int)e.KeyChar == 53 || (int)e.KeyChar == 54 || (int)e.KeyChar == 55 || (int)e.KeyChar == 56 || (int)e.KeyChar == 57) 
    e.Handled = false;     else 
    e.Handled = true;