AlphaNumeric String Increment in C#

In order to do that we 1st need to Know about the substring.

Substring in C# string Class returns a new string that is a substring of this string. The substring begins at the specified given index and extended up to the given length.

string string.substring(int startIndex,int length)

Parameters

  • startIndex: The index of the start of the substring.
  • length: The number of characters in the substring.

Returns:

The specified substring.

Program and its code:

  1. Create a new windows form.

  2. Drag an Drop the Textbox and Button field on to the windows form.

  3. Fill the Textbox Data as "CP000".

  4. Now we will write code for the button click event. In this code we will try to increment the textbox data.

    In the following manner CP000,CP001,CP002,.....CP011,CP012,......CP998,CP999.

  5. Declare a global variable in the form and name it as:
    1. public string str;   
    2.   
    3. and assign textboxt1.text = str;  
  6. Button Click Event code.
    1. private void btnIncrement_Click(object sender, EventArgs e)  
    2. {  
    3.     int Num1 = Convert.ToInt32(textBox1.Text.Substring(4, 1));  
    4.     int Num2 = Convert.ToInt32(textBox1.Text.Substring(3, 2));  
    5.     int Num3 = Convert.ToInt32(textBox1.Text.Substring(2, 3));  
    6.     if (Num1 < 9)  
    7.     {  
    8.         int Num = Num1 + 1;  
    9.         str = str.Substring(0, 4) + Num;  
    10.         textBox1.Text = str;  
    11.     }  
    12.     else if (Num2 < 99)  
    13.     {  
    14.         int Num = Num2 + 1;  
    15.         str = str.Substring(0, 3) + Num;  
    16.         textBox1.Text = str;  
    17.     }  
    18.     else if (Num3 < 999)  
    19.     {  
    20.         int Num = Num3 + 1;  
    21.         str = str.Substring(0, 2) + Num;  
    22.         textBox1.Text = str;  
    23.     }  
    24. }  
  7. Enjoy the programming.