Click here to Skip to main content
15,905,877 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i Try AutoNumber for My Database in C#, But i Have A Problem in My AutoNumber Code,

Problem in AutoNumber

SrNo
00001
00002
00003
00004

if I Delete SrNo 00001 DataSet Then Next AutoNumber Show 00004 in TextBox but I Need Next Number Show in TextBox 00005

Can Any one Help Me and Fix My Problem

What I have tried:

My Code
private void Autonumber()
        {
            String connstring = ConfigurationManager.ConnectionStrings["Data"].ConnectionString;
            OleDbConnection con = new OleDbConnection(connstring);
            string Query = "select count(*) from customer";
            OleDbCommand cd = new OleDbCommand(Query, con);
            try
            {
                con.Open();
                int count = Convert.ToInt16(cd.ExecuteScalar()) + 1;
                txtNumber.Text = count.ToString("00000");
                txtNumber.Enabled = false;
                
            }
            
            finally
            {
                con.Close();
            }
        }
Posted
Updated 6-May-20 2:08am
v2
Comments
Amar chand123 6-May-20 6:10am    
Now i try remove "Count" and use "max" in statement and is worked, us that right or not
Richard MacCutchan 6-May-20 6:34am    
No, you should let the database generate sequence numbers automatically. I cannot recall the exact syntax but you need to declare one column of your customer table to be auto generated.
Maciej Los 6-May-20 8:09am    
My virtual 5!
Richard MacCutchan 6-May-20 8:22am    
Thanks, but it's only worth a 5 if I can remember the exact syntax.
Maciej Los 6-May-20 8:42am    
Who cares about exact syntax? More important is to suggest an idea!

You can use:
SELECT MAX(SrNo) FROM customer

See: SQL MIN() and MAX() Functions[^]
 
Share this answer
 
Comments
Maciej Los 6-May-20 8:09am    
5ed!
In single-user-environment custom autonumber function would be OK. But in multi-user-environment, it would fail.

You should implement what Richard MacCutchan mentioned in the comment to the question. See:
SQL SERVER 2012 – How to generate a varchar Sequence Number – Using Sequence Object | SQL Server Portal[^]

In case when database is placed is an Excel or Access file, you're in trouble. There's no such of functionality. You have to write custom function. See RickZeeland solution for details. Here is how to achieve that:
NextSrNo = MAX(SrNo) +1
 
Share this answer
 
v2

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