Click here to Skip to main content
15,891,778 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i use this Code for Generate AutoNumber but i have a Problem when i start enter new Data in DataBase AutoNumber Not Work if i Not have any data in my DataBase, if only work when i have 00001 in my DataBase but if i start form Zero then it's Not Work

What I have tried:

C#
private void Autonumber()
        {
            String connstring = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
            OleDbConnection con = new OleDbConnection(connstring);
            string Query = "select MAX(ReceiptNo) from Data";
            OleDbCommand cd = new OleDbCommand(Query, con);
            
            {
                con.Open();
                int count = Convert.ToInt16(cd.ExecuteScalar()) + 1;
                txtRecd.Text = count.ToString("00000");
                txtRecd.Enabled = false;

            }

            
        }
Posted
Updated 27-May-20 21:14pm
v3

You should use an auto-incremented column on the database itself. Generating id's on client side becomes quicly subject to errors whenever there are more than one user.
 
Share this answer
 
Comments
Amar chand123 28-May-20 2:48am    
Only one user Project and auto incremented column problem is if i have 10 data in database and i delete last 7 data and add new data in database then SrNo is show 11 not 7
phil.o 28-May-20 3:42am    
This is a common non-issue. You should not care that your ids in the database are not contiguous. They are not meant to make your data pretty, they are meant to index a row unambiguously. Strict continuity of numeric ids is nothing else than cosmetic.
Phil.o's answer is the recommended way, but you could also try something like this:
var obj = cd.ExecuteScalar();
var count = (obj == DBNull.Value ? 0 : Convert.ToInt32(obj));

If your table is empty the ExecuteScalar will return a DBNull.Value.
 
Share this answer
 
v4
Comments
Amar chand123 28-May-20 2:44am    
Not working
RickZeeland 28-May-20 3:10am    
Corrected the answer, you probably need to use DBNull.Value instead of Null.
Amar chand123 28-May-20 4:46am    
Thank you

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