'how to generate sequence number using c# in window application

       private string GenerateID()
        {


        }
        private void auto()
        {
            AdmissionNo.Text = "A-" + GenerateID();

        }

with prefix of A like below A-0001 A-0002 and so on .



Solution 1:[1]

You can use below code.

private string GenerateId()
{
    int lastAddedId = 8; // get this value from database
    string demo = Convert.ToString(lastAddedId + 1).PadLeft(4, '0');
    return demo;
    // it will return 0009
}

private void Auto()
{
    AdmissionNo.Text = "A-" + GenerateId();
    // here it will set the text as "A-0009"
}

Solution 2:[2]

Look at this

public class Program
{
    private static int _globalSequence;

    static void Main(string[] args)
    {
        _globalSequence = 0;

        for (int i = 0; i < 10; i++)
        {
            Randomize(i);
            Console.WriteLine("----------------------------------------->");
        }


        Console.ReadLine();
    }

    static void Randomize(int seed)
    {
        Random r = new Random();
        if (_globalSequence == 0) _globalSequence = r.Next();

        Console.WriteLine("Random: {0}", _globalSequence);
        int localSequence = Interlocked.Increment(ref _globalSequence);

        Console.WriteLine("Increment: {0}, Output: {1}", _globalSequence, localSequence);
    }

}

Solution 3:[3]

Whether it is an windows application or not is IMHO not relevant. I'd rather care about thread safety. Hence, I would use something like this:

public sealed class Sequence
{
    private int value = 0;

    public Sequence(string prefix)
    {
        this.Prefix = prefix;
    }

    public string Prefix { get; }

    public int GetNextValue()
    {
        return System.Threading.Interlocked.Increment(ref this.value);
    }

    public string GetNextNumber()
    {
        return $"{this.Prefix}{this.GetNextValue():0000}";
    }
}

This could easily be enhanced to use the a digit count. So the "0000" part could be dynamically specified as well.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fred
Solution 2 DanielV
Solution 3 TiltonJH