How to generate 5 different random number in asp.net webforms

How to generate 5 different random number in textbox by only 1 button?

protected void Button1_Click(object sender, EventArgs e)
        {
            Random r = new Random();
            int num = r.Next();      
            TextBox1.Text = num.ToString();
            TextBox2.Text = num.ToString();
            TextBox3.Text = num.ToString();
            TextBox4.Text = num.ToString();
            TextBox5.Text = num.ToString();
        }

I understand with this will only get same number, but is there any way to get different number?

3 answers

  • answered 2021-02-21 16:56 Hardik Shah

    You can just put r.Next() in loop like below example:

        string printmsg = string.Empty;
        int[] x = new int[5];
        Random r = new Random();
        for (int i = 0; i < 5; i++)
        {
            x[i] = r.Next();
            printmsg += x[i] + ",";
        }
        lblMsg.Text = printmsg.Substring(0, printmsg.Length-1);
    

    And then use it in array or string or different textboxes as you wish.

  • answered 2021-02-21 17:10 Jamwit Karimov

    You can add every generated number to List. Then check contains or not.

                        Random r = new Random();
                        var list = new List<int>(5);
                        for (int i = 0; i < 5; i++)
                        {
                            var num = r.Next(5);
                            if (!list.Contains(num)) //If not add to list 
                            {
                                list.Add(num);
                            }
                            else //If contains return back and generate again.
                            {
                                i--; 
                            }
                        }
                      //It will more effective if you convert this section into loop. 
                        Textbox1.Text = list[0].ToString();
                        Textbox2.Text = list[1].ToString();
                        Textbox3.Text = list[2].ToString();
                        Textbox4.Text = list[3].ToString();
                        Textbox5.Text = list[4].ToString();
    

  • answered 2021-02-21 17:20 Denis K.

    Short example with randomizer initialization

        static void Example()
        {
              var textBoxes = new List<TextBox> { Textbox1, Textbox2, Textbox3, Textbox4, Textbox5 };
              // GUID will produce better randomization
              var rand = new Random(Guid.NewGuid().GetHashCode());        
              foreach (var textBox in textBoxes)
                    textBox.Text = rand.Next().ToString();
         }