Here, we will see how to generate random password in ASP.NET. Drag and drop two TextBox and one Control on the form. One TextBox to give the length of the TextBox other to displays random password according to length when we click on the Button control.
The form looks like below figure.
Figure1
.ASPX code
<body>
<form id="form1" runat="server">
<div>
Password Length:
<asp:TextBox ID="txtPassLength" runat="server"></asp:TextBox>
<br />
<br />
Random Password:
<asp:TextBox ID="txtpassword" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Generate Password" />
<br />
</div>
</form>
</body>
Now double click on the Button control and add the following code.
VB code
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim allowedChars As String = ""
allowedChars = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,"
allowedChars += "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,"
allowedChars += "1,2,3,4,5,6,7,8,9,0,!,@,#,$,%,&,?"
Dim sep As Char() = {","c}
Dim arr As String() = allowedChars.Split(sep)
Dim passwordString As String = ""
Dim temp As String = ""
Dim rand As New Random()
For i As Integer = 0 To Convert.ToInt32(txtPassLength.Text) - 1
temp = arr(rand.[Next](0, arr.Length))
passwordString += temp
Next
txtpassword.Text = passwordString
End Sub
C# code
protected void Button1_Click(object sender, EventArgs e)
{
string allowedChars = "";
allowedChars = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,";
allowedChars += "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,";
allowedChars += "1,2,3,4,5,6,7,8,9,0,!,@,#,$,%,&,?";
char[] sep = { ',' };
string[] arr = allowedChars.Split(sep);
string passwordString = "";
string temp = "";
Random rand = new Random();
for (int i = 0; i < Convert.ToInt32(txtPassLength.Text); i++)
{
temp = arr[rand.Next(0, arr.Length)];
passwordString += temp;
}
txtpassword.Text = passwordString;
}
Now run the application.
Figure2
Now give the length of the password.
Figure3
Now click on the Button to generate random password.
Figure4