Click here to Skip to main content
15,896,500 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
i want to generate auto number in every form by using one function...how can i do it....
Posted

Do you want to do this at the client level?

If so use a static member field of int type. And increment it in a getter. Use locking to make it thread safe.

Quickly put together untested sample code:

C#
static class AutoNumber
{
    static object synclock = new object();

    static int number = 0;

    public static int Next
    {
        get
        {
            lock(synclock)
            {
                return ++number;
            }
        }
    }
}


Alternate approach without the lock:

C#
static class AutoNumber
{
    static int number = 0;

    public static int Next
    {
        get
        {
            return Interlocked.Increment(ref number);
        }
    }
}
 
Share this answer
 
v3
Comments
Rick Shaub 18-Apr-11 13:43pm    
My 5. Great answer. I would make synclock readonly as well.
thatraja 18-Apr-11 13:47pm    
Good answer. 5!
BTW I have answered about Random (Actually I need to take coffee now, that's why....*In tired*). After seen your answer only I re-read the question(asked for Auto number.). Deleted my answer.
Sergey Alexandrovich Kryukov 18-Apr-11 16:29pm    
Agree, my 5.
Taking care of threading is also good (potentially, as OP did not show any signs of using it from different threads).
--SA
Espen Harlinn 18-Apr-11 17:45pm    
Nice reply, my 5
Nish Nishant 18-Apr-11 18:14pm    
Thanks!
Your number should be a singleton, see http://en.wikipedia.org/wiki/Singleton_pattern[^].

Simply make a class for it and make the number a static private integer member, return it and increase on each request.

—SA
 
Share this answer
 
Comments
thatraja 18-Apr-11 13:48pm    
Also it's a good answer. Have 5 SA.
Sergey Alexandrovich Kryukov 18-Apr-11 16:29pm    
Thank you very much.
--SA
Espen Harlinn 18-Apr-11 17:46pm    
Good idea, my 5
Sergey Alexandrovich Kryukov 18-Apr-11 22:19pm    
Thank you, Espen.
--SA
Monjurul Habib 19-Apr-11 3:13am    
nice answer.my 5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900