Monday, April 9, 2012

Unique Random Number Generation in asp.net



using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    private static Random random = new Random((int)DateTime.Now.Ticks);
    protected void Page_Load(object sender, EventArgs e)
    {
        // get 1st random string
        string RandNum1 = RandomStringMehtod(4);

        // get 2nd random string
        string RandNum2 = RandomStringMehtod(4);

        // create full random string
        string FinalNum = RandNum1 + "-" + RandNum2;
    }

    private string RandomStringMehtod(int size)
    {
        StringBuilder sb = new StringBuilder();
        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            sb.Append(ch);
        }

        return sb.ToString();
    }
}


No comments:

Post a Comment