How can I automatically increment numbers in C#?

32,455

Solution 1

Quite easy. Keep a variable to keep the current number.

int incNumber = 0;

Then on click of button, generate the number string like this:

string nyNumber = "s" + incNumber.ToString("00");
incNumber++;

Solution 2

Do as suggested by Øyvind Knobloch-Bråthen but if you want it to be done automatically when form is Deactivated and Activated (You come back to the form and give it focus) then you can do somthing like this.

This only works if you are sure the text in box will always be in the mentioned format

this.Activated += (s, ev)=>{ 
         string tmp = textbox1.Text; 
         int num = String.Substring(1) as int;              
         if(nuum != null) 
         {
             num++;
             textbox1.Text = "s" + num.Tostring();  
         }
      };

Solution 3

Just as Øyvind Knobloch-Bråthen said: Keep track of the integer using a variable. Only you should format it like this (Microsoft preferred):

int incNumber = 0;

string formattedIncNumber = String.Format("s{0:D2}", incNumber);
incNumber++;

Or if you want to do it with one line less code:

int incNumber = 0;

string formattedIncNumber = String.Format("s{0:D2}", incNumber++);

See MSDN for a complete reference for formatting integers.

Solution 4

A slightly better variation of oyvind-knobloch-brathen's above:

int incNumber=0;
s + String.Format("{0:00}", incNumber);  
incNumber++;

//s00, s01, s02. If you want, say, the range 0001-9999, just change "00" to "0000", etc.

Solution 5

If the text component of the string is unknown (with or without a number at the end of the string), variations of this function may be helpful:

        private string increment_number_at_end_of_string(string text_with_number_at_the_end)
        {
            string text_without_number = text_with_number_at_the_end.TrimEnd('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
            string just_the_number = text_with_number_at_the_end.Substring(text_without_number.Length);

            int number = -1;
            if (int.TryParse(just_the_number, out number))
            {
                return text_without_number + (number + 1).ToString();
            }
            return text_with_number_at_the_end;
        }
Share:
32,455
vamshi
Author by

vamshi

Updated on August 06, 2020

Comments

  • vamshi
    vamshi almost 4 years

    I am using C# 2008 Windows Forms application.

    In my project there is a TextBox control and in that I want make an auto generate numbers for samples s00, next when I come back to form again it should be increment like s01,s02,s03......like that

    Please help me

  • Ray Booysen
    Ray Booysen over 13 years
    I think you still need to increment the number though. ;)
  • Victor Zakharov
    Victor Zakharov over 11 years
    OP is not dealing with databases.
  • Alexander Leonov
    Alexander Leonov about 7 years
    What does it have to do with the question?