Keep (retain) generated number on Button Click using C# in ASP.Net

Last Reply one month ago By nagaraju60

Posted one month ago

I have a reference number that is auto generated when a web page is loaded, but each time I click on a button on the page the reference number changes. Is it possible to keep the first number that is generated and stop it from changing?

        protected void Page_Load(object sender, EventArgs e)
        {
            string numbers = "1234567890";

            string characters = numbers;
            int length = 7;
            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;
            }
            Labelreceipt.Text = id;
        }

 

Posted one month ago Modified on one month ago

Use the code inside the !this.IsPostBack condition.


Posted one month ago Modified on one month ago

Hi @George616,

Please refer below code

        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                string numbers = "1234567890";

                string characters = numbers;
                int length = 7;
                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;
                }
                Labelreceipt.Text = id;
            }
        }