Generate a string with first 4 characters constant and remianing a Random AlphaNumeric string in C# .Net

Last Reply on May 05, 2014 06:03 AM By Azim

Posted on May 05, 2014 01:50 AM

How to auto generate Unique Id whose starting 3 or 4 letters can be changed as per requirement.

I had tried below code but it auto generates the unique numbers + letters.

 

Random objRandom = new Random();

protected void GetRefnum()
        {           
            List<int> ints = new List<int>();
            for (int i = 0; i < 10; i++)
            {
                int randomNumber;
                string strTemp;

                randomNumber = objRandom.Next(1, 30);
                strTemp = (string)Microsoft.VisualBasic.Interaction.Choose(randomNumber, "B", "1", "D", "2", "F", "3", "0", "4", "a", "5", "j", "6", "K", "7", "L", "8", "m", "9", "N", "p", "X", "Y", "#", "G", "H", "R", "w");
                strRef += strTemp;
                i++;
                LRef.Text = strRef;
            }
        }

Which is not my requirement.

I want that I should change the staring 4 letters(as per my requirement) and then after 4 letters, code should generate unique numbers+letters

Please reply.

Posted on May 05, 2014 06:03 AM Modified on on May 06, 2014 05:50 AM

Ref

http://stackoverflow.com/questions/1344221/how-can-i-generate-random-alphanumeric-strings-in-c

HTML

<asp:TextBox ID="txtNumber" runat="server" />
<asp:Button Text="Generate" runat="server" OnClick="GenerateNumber" />
<hr />
<asp:Label ID="lblRandomNumber" runat="server" />

C#

protected void GenerateNumber(object sender, EventArgs e)
{
    string randomCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    Random random = new Random();
    var result = new string(
        Enumerable.Repeat(randomCharacters, 5)
                    .Select(s => s[random.Next(s.Length)])
                    .ToArray());
    this.lblRandomNumber.Text = this.txtNumber.Text.Trim() + result.ToString();
}

Screenshot