0

I need a serial number to be stored in data base with a record when I click a button, so far I did this and it works it generates serial number ,but the problem when I exit the app and start again the serial number starts from 0 again and that doesn't work because in the database its primary key. so I need it to continue where it left off. im sorry if im not explaining well

public static class SequentialNumber
{
   private static int id=0;
   public static string GetId()
   {
        id++;
        return id.ToString();
   }
 }
carl
  • 9
  • 1
  • I think the question doesnt fit stackoverflow and noone will write code for you. You need to search tutorials on how to connect with your database through c#. – Michail Michailidis Jul 07 '18 at 09:04
  • 1
    You can fetch the last stored serial from the database and insert with new row after increasing it by one. A simple way is to use identity column in your table if you are using SQL Server. – Vikram Kumar Jul 07 '18 at 09:08
  • @MichailMichailidis I don't need anyone to write me a code, and I am already connected to database – carl Jul 07 '18 at 09:10
  • @VikramKumar do you mean I can fetch the id that the user have entered? ill try that – carl Jul 07 '18 at 09:12
  • @carl Correct! Get the last inserted serial number before inset, increase it and then insert with new record. Good Luck. – Vikram Kumar Jul 07 '18 at 09:16

1 Answers1

3

You have multiple approaches to solve this issue

  1. Set Your Primary Key column to Auto Increment column that'll give you your serial number in DB only no need to write And c# code for that.
  2. Store last serial number on application Exit then Read last available serial number from DB and load
  3. Use file instead of Database

Note:- if the file where counter is stored is be deleted then counter will start from 0

public static class SequentialNumber
{
    private static int id=0;
    public static string GetId()
    {
        if(id==0)
        {
            Int32.TryParse(File.ReadAllText("count.txt"),out id);
        }
        id++;
        File.WriteAllText("count.txt", id.ToString());
        return id.ToString();
    }
}
Mihir Dave
  • 3,954
  • 1
  • 12
  • 28