Skip to main content

Random Code Generator using C#


In this tutorial, I will teach you how to create a program that will generate a random code or id using the C# language.


So, now let's start this tutorial!

1. Let's start with creating a Windows Form Application for this tutorial by following the following steps in Microsoft Visual Studio 2010: Go to File, click New Project, and choose Windows Application.

2. Add one textbox named txtIDno and one button named btnGenerate.

design

3. Now, create a function named generateCode. Have this code below.

  1. void generateCode()
  2. {
  3. //Initialize variable x as an empty string and a rand varaiable as Random
  4. String x = "";
  5. Random rand = new Random();
  6. // The z string variable holds the current year
  7. string z = Convert.ToString(DateTime.Now.Year);
  8.  
  9.  
  10. // This loop creates 2 random numbers at first and concatenates the STI word after the 2 random numbers
  11. // And also it only generates a number from 0-9
  12. for (int y = 1; y <= 2; y++)
  13. {
  14. x += Convert.ToString(rand.Next(0, 9));
  15. if (y == 2)
  16. {
  17. x += "STI-";
  18. }
  19.  
  20. }
  21.  
  22. // This loop creates 3 random numbers from 0-9
  23. for (int y = 1; y <= 3; y++)
  24. {
  25. x += Convert.ToString(rand.Next(0, 9));
  26. }
  27. //display the generated code in the textbox
  28. txtIDno.Text = z + "-" + x;
  29. }

Lastly, put your function in your button.

  1. private void btnGenerate_Click(object sender, EventArgs e)
  2. {
  3. if (txtIDno.Text == "")
  4. {
  5. generateCode();
  6. }
  7. }

Output:

output

For more inquiries and need programmer for your thesis systems in any kind of programming languages, just contact my number below.

Best Regards,

Engr. Lyndon R. Bermoy
IT Instructor/System Developer/Android Developer
Mobile: 09079373999
Telephone: 826-9296
E-mail:[email protected]

Visit and like my page on Facebook at: https://www.facebook.com/BermzISware

Subscribe at my YouTube Channel at: Ser Bermz

Visit my website at: www.campcodes.com

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.