Pages

Wednesday, August 21, 2013

how to generate random number when you click on refresh button in .net?

This article will explain how to generate a random number

Add new item it solution explorer

drag and drop the text box and label
.aspx page:
design mode:
aspx
source:
<table><tr><td>RANDOM NUMBER:</td><td><asp:TextBox ID="txtrobocomp" runat="server"  Font-Names="Vivaldi"
                        Font-Size="X-Large" Font-Bold="True" BackColor="#CC99FF" ForeColor="#CC0066"
                        Width="148px" Height="33px"></asp:TextBox></td></tr>

code in .aspx.cs page:
private int RandomNumber(int min, int max)
    {
        Random rd = new Random();
        return rd.Next(min, max);
    }

    private string RandomString(int size, bool lowerCase)
    {
        StringBuilder builder = new StringBuilder();
        Random rd = new Random();
        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * rd.NextDouble() + 65)));
            builder.Append(ch);
        }
        if (lowerCase)
            return builder.ToString().ToLower();
        return builder.ToString();
    } 

The output will be seen like this

random
After refreshing the page randomnumber will be generated
Place a refresh button in .aspx page
Image will shown like this
refresh
code in .aspx.cs page
in page load event
 protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(RandomNumber(10, 99));
            builder.Append(RandomString(3, true));
            builder.Append(RandomString(2, false));
            txtrobocomp.Text = builder.ToString();
        }
    }
code in refresh button click event
 protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            //if (!Page.IsPostBack)
            //{
                StringBuilder builder = new StringBuilder();
                builder.Append(RandomNumber(10, 99));
                builder.Append(RandomString(3, true));
                builder.Append(RandomString(2, false));
                txtrobocomp.Text = builder.ToString();
            //}
         }

the output will be like this
 
After clicking on refresh button the same as our captcha image
the output will be like this the random number is changed in particular text box
If you click on refresh button the random number will be generated by using the code above we can generate a random number and refresh button it will be seen like our captcha image

I hope you understand this article and will be useful. 

No comments:

Post a Comment