How To Generate Random Numbers In Asp.Net
In this tutorial we will let you know How To Generate Random Numbers In Asp.Net.Here we will demonstrate two methods for this.On first we are generating only random numbers, on second method we are generating number with alphabet.This is a very simple approach.
Design View:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body style="margin:0px auto;padding:100px;width:900px;font-family:Calibri"> <form id="form1" runat="server"> <div style="text-align:center"> <h3>Only Number: <asp:Label ID="number" ForeColor="red" runat="server"></asp:Label></h3> <br /><br /> <h3>Number With Alphabet: <asp:Label ID="number1" ForeColor="red" runat="server"></asp:Label></h3> <br /><br /> <asp:Button ID="generate" Text="Generate New Numbers" runat="server" OnClick="generate_Click" /> </div> </form> </body> </html>
Code View:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { int ranid = RandomNumber(00000, 9999999); number.Text = ranid.ToString(); randomnumber1(); } private int RandomNumber(int min, int max) { Random random = new Random(); return random.Next(min, max); } public void randomnumber1() { String guid = ""; String allowchars = " "; allowchars = "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"; allowchars += "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"; allowchars += "1,2,3,4,5,6,7,8,9,0"; char[] sep = { ',' }; String[] arr = allowchars.Split(sep); String temp = ""; Random rnd = new Random(); for (int i = 0; i < 8; i++) { temp = arr[rnd.Next(0, arr.Length)]; guid += temp; } number1.Text = guid.ToString(); } protected void generate_Click(object sender, EventArgs e) { Response.Redirect(Request.RawUrl); } }
One reply on “How To Generate Random Numbers In Asp.Net”
I was extremely pleased to discover this web-site.I wanted to thanks for your time for this terrific read!! I unquestionably enjoying every little bit of it and I’ve you bookmarked to check out new stuff you weblog post.