Click here to Skip to main content
15,887,446 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i try AutoNumber in TextBox From SqlDataBase,
but Problem Appear when AutoNumer Reach Number 10 after Number my AutoNumber Code show every Time Number 10

when i use Debug

C#
var cont = cd.ExecuteScalar();
Var cout show Value = 9


What I have tried:

My Code is:
C#
// AutoNumber
        private void Autonumber()
        {
            string Query = "select MAX(ReceiptNo) from Project1";
            SqlCommand cd = new SqlCommand(Query, con);
            try
            {
                con.Open();
                var cont = cd.ExecuteScalar();
                var count = (cont == DBNull.Value ? 1 : Convert.ToInt32(cont) + 1);
                txtRecpt.Text = count.ToString();
            }

            finally
            {
                con.Close();
            }
        }
Posted
Updated 6-Sep-20 22:59pm
v2
Comments
F-ES Sitecore 7-Sep-20 5:34am    
If your query is returning 9 then that is the biggest instance of ReceiptNo in the database so your problem lies elsewhere. If you think it should be more then check where\how you create new rows, but as already told in the solutions trying to do your own auto number is generally very bad practice.
Amar chand123 7-Sep-20 5:38am    
Problem solved mistake in 'ReceiptNo' data type when i change column data type into 'INT' problem solved

1 solution

Ignore the problem you have spotted - you have much worse.

What you are doing is a very bad idea: never "preallocate" numbers and assume they will work as an autonumber.

Think about it: SQL Server is a multiuser system: which means that multiple applications on multiple computers can access the same database at the same time.
Suppose you call Autonumber and get "123". I also call Autonumber from my computer and also get "123" because the database hasn't been changed yet.
One of use will INSERT a new record correctly, one of us won't. And if any other information references that autonumber (for example, InvoiceLines referencing an Invoice) then your info gets "mixed in" with mine because they are both using the same "autonumber".

Instead, use an IDENTITY column in your database and let SQL take care of it: you INSERT the row, it allocates the unique autonumber, and nothing ever gets messed up.

Don't try to do it yourself, it will end in tears.
 
Share this answer
 

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