Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I automatically increment numbers in C#?

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

like image 1000
vamshi Avatar asked Feb 04 '11 11:02

vamshi


People also ask

What is i ++ and ++ i in C?

In C, ++ and -- operators are called increment and decrement operators. They are unary operators needing only one operand. Hence ++ as well as -- operator can appear before or after the operand with same effect. That means both i++ and ++i will be equivalent.

What is auto increment in C?

Auto increment and decrement One of the nicer shortcuts is the auto-increment and auto-decrement operators. You often use these to change loop variables, which control the number of times a loop executes. The auto-decrement operator is '--' and means “decrease by one unit.”

How do you increment a number?

1. The process of increasing or decreasing a numeric value by another value. For example, incrementing 2 to 10 by the number 2 would be 2, 4, 6, 8, 10. 2.

What is post-increment in C?

2) Post-increment operator: A post-increment operator is used to increment the value of the variable after executing the expression completely in which post-increment is used. In the Post-Increment, value is first used in an expression and then incremented. Syntax: a = x++;


2 Answers

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++;
like image 102
Øyvind Bråthen Avatar answered Oct 08 '22 05:10

Øyvind Bråthen


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();  
         }
      };
like image 44
Shekhar_Pro Avatar answered Oct 08 '22 04:10

Shekhar_Pro