Here i have explained how to Generate Random String or Number in Asp.Net C#.

Step 1) Add HTML:

<div>
    Enter Number: <asp:TextBox ID="txtCharacters" runat="server"/>
    <asp:Button ID="btnGenerate" Text="Generate" runat="server" 
            onclick="btnGenerate_Click" /><br />
            <asp:Label ID="lblResult" runat="server" ForeColor="Red" />
    </div>

Step 2) Import Namespaces

using System;
using System.Web;

Step 3) C#

    protected void btnGenerate_Click(object sender, EventArgs e)
{
// declare array string to generate random string with combination of small,capital letters and numbers
char[] charArr = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();

string strrandom = string.Empty;
Random objran = new Random();
int noofcharacters = Convert.ToInt32(txtCharacters.Text);
for (int i = 0; i < noofcharacters; i++)
{
//It will not allow Repetation of Characters
int pos = objran.Next(1, charArr.Length);
if (!strrandom.Contains(charArr.GetValue(pos).ToString()))
strrandom += charArr.GetValue(pos);
else
i--;
}
lblResult.Text = strrandom;
}

Screenshot

Add Comments