Auto-generated Reference number repeats itself more than twice

Donald Symmons 3,066 Reputation points
2024-10-15T04:23:38.9766667+00:00

Hello,

I have been trying to create an automated Reference number that can be used to identify each user but in some aspect, there is a repetition in the number.

From my code, the Reference number is supposed to be unique but there are multiple of the same Reference number. How can I create a unique Reference number that cannot be repeated?

For example, if a Reference number like 539873321 exists in the database table, it should generate a new one. But whenever I go to the page a new Reference number is created and in some cases it repeats the same number and I will have like 3 of the same Reference number 539873321

Please I want to create an auto-generated Reference number that cannot be repeated, How can I do that please?

*Here is my code to generate number automatically without repeating the same number

protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                AutoGenerateNumber();
            }
        }

This code generates 9-digit automatic reference number

private string GetAutoNumber()
        {
            string numbers = "1234567890";
            string characters = numbers;
            int length = 9;
            string id = string.Empty;
            for (int i = 0; i < length; i++)
            {
                string character = string.Empty;
                do
                {
                    int index = new Random().Next(0, characters.Length);
                    character = characters.ToCharArray()[index].ToString();
                } while (id.IndexOf(character) != -1);
                id += character;
            }

            return id;
        }

This code is where is search the database table to see if the reference number exists, then it should generate another reference number

private void AutoGenerateNumber()
        {
            try
            {
                using (SqlConnection con = new SqlConnection())
                {
                    con.ConnectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
                    SqlDataReader dr;
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.Parameters.Clear();
                        cmd.CommandText = "SELECT reference_no FROM IDTable WHERE 
reference_no=@reference_no"; // Here I tried to check the table to see if the Reference number numbers exist. And if it exists then it should automatically create a new one                         cmd.Parameters.AddWithValue("@Reference_no", ReferenceLabel.Text);
                        cmd.Connection = con;
                        con.Open();
                        dr = cmd.ExecuteReader();
                    }
                    if (dr.HasRows)
                    {
                       
                    }
                    else
                    {
                        List<string> result = new List<string>();
                        if (Session["Numbers"] != null)
                        {
                            result = (List<string>)Session["Numbers"];
                        }

                        string number = GetAutoNumber();
                        if (!result.Contains(number))
                        {
                            result.Add(number);
                            Session["Numbers"] = result;
                            ReferenceLabel.Text = number;                         }
                    }
                }
            }
            catch (SqlException ex)
            {
                string msg = "Error:";
                msg += ex.Message;
                throw new Exception(msg);
            }
        }

Developer technologies .NET Other
Developer technologies ASP.NET Other
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Lan Huang-MSFT 30,186 Reputation points Microsoft External Staff
    2024-10-15T07:22:49.9133333+00:00

    Hi @Donald Symmons,

    You can't use Session to achieve this because the Session will be cleared when the application stops.

    You can determine if the generated auto-generated reference number already exists in the database. If so, you can re-run the GetAutoNumber() method.

     private void AutoGenerateNumber()
     {
         try
         {
             string number = GetAutoNumber();
             using (SqlConnection con = new SqlConnection())
             {
                 con.ConnectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
                 SqlDataReader dr;
                 using (SqlCommand cmd = new SqlCommand())
                 {
                     cmd.Parameters.Clear();
                     cmd.CommandText = "SELECT reference_no FROM IDTable WHERE reference_no = @reference_no"; // Here I tried to check the table to see if the Reference number numbers exist. And if it exists then it should automatically create a new one
                     cmd.Parameters.AddWithValue("@Reference_no", number);
                     cmd.Connection = con;
                     con.Open();
                     dr = cmd.ExecuteReader();
                 }
                 if (dr.HasRows)
                 {
                     string newnumber = GetAutoNumber();
                     //Insert a new number
                 }
                 else
                 {
                 }
             }
         }
         catch (SqlException ex)
         {
             string msg = "Error:";
             msg += ex.Message;
             throw new Exception(msg);
         }
     }
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread

    1 person found this answer helpful.

3 additional answers

Sort by: Most helpful
  1. SurferOnWww 4,631 Reputation points
    2024-10-15T06:01:49.65+00:00

    How about using GUID?

    1 person found this answer helpful.

  2. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2024-10-15T15:30:15.4266667+00:00

    your code only works if you website has only one user. two concurrent users will get the same number. you need to change your code so that the new number is saved in the database in the same transaction that creates it. this generally will cause gaps, as a user may be assigned a number, but need complete the transactions.

    if gaps are an issue, then the unique number should not be assigned until the first transaction save.

    note: there should also be a unique index, so duplicates can not be created.

    1 person found this answer helpful.

  3. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.

    2 deleted comments

    Comments have been turned off. Learn more

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.