How can I automatically increment numbers in C#?

空扰寡人 提交于 2019-12-01 16:17:59
Øyvind Bråthen

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++;

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();  
         }
      };

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.

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.

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;
        }
Ritesh Desai

Try This For auto generation of number and auto incrementation of number:

// Stock is table name
// metal id is unique number that is auto generated as well as auto incremented


private void textBox9_TextChanged(object sender, EventArgs e)
{
    string s = "select max(metalid)+1 from stock";
    SqlCommand csm = new SqlCommand(s, con);

    con.Open();
    csm.ExecuteNonQuery();

    SqlDataReader dd = csm.ExecuteReader();

    while (dd.Read())
    {
        int n = dd.GetInt32(0);
        textBox1.Text = n.ToString();
    }

     con.Close();
}

Another single line approach would be:

string sampleNum = "s" + (counter++).ToString("00");

Where counter defines like this:

int counter= 0;

This is the solution to generator auto incremented id in C# which don't need to increase or do anything. It will just work. whenever a new object created its value will increase by 1.

public class Employee
    {
        static long AutoId = 0;
        public long Id { get; private set; } = ++AutoId;
        public string EmployeeName { get; set; }
        public string Address { get; set; }
    }
{  try {  //madhura//  SqlCommand cmd1 = new SqlCommand(@"select 'Column_name'+ REPLACE(STR(MAX(CAST(Right(Column_name,5) as int)+1 ),6),SPACE(1),'0') as Column_name from TabelName ", con);  SqlDataAdapter da = new SqlDataAdapter(cmd1);   DataTable dt = new DataTable();  da.Fill(dt);

if (dt.Rows[0][" Column_name'"].ToString() == null) { Label1.Text = "DMBP-000001"; } else{ Label.Text= dt.Rows[0][" Column_name'"].ToString(); } } catch { } }

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!