Random the value of textbox

BgnerNprg207 286 Reputation points
2024-03-06T12:38:44.0533333+00:00

Attention Master, I need help.

User's image

as you can see at the top I have a form, 3 textbox with the value of 1,2,3 for example only.

and in the left side they have a list view and the button name "Generate". Now I want is If I click generate button the value of each textbox will random and display in the list box.

I hope any one can help to fix this problem, Thank you so much.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiale Xue - MSFT 43,046 Reputation points Microsoft Vendor
    2024-03-06T14:30:17.16+00:00

    Hi @BgnerNprg207 , Welcome to Microsoft Q&A,

    Sure, use random.Next etc. to randomly generate numbers. Just add it to the listbox.

    using System;
    using System.Windows.Forms;
    
    namespace xxx
    {
         public partial class Form1 : Form
         {
             public Form1()
             {
                 InitializeComponent();
             }
    
             private void button1_Click(object sender, EventArgs e)
             {
                 // Clear ListBox and TextBoxes
                 listBox1.Items.Clear();
                 textBox1.Clear();
                 textBox2.Clear();
                 textBox3.Clear();
    
                 // Generate three random numbers and add them to ListBox and TextBoxes
                 Random random = new Random();
                 for (int i = 0; i < 3; i++)
                 {
                     int randomNumber = random.Next(1, 101); // Generate a random integer between 1 and 100
                     listBox1.Items.Add(randomNumber);
    
                     //Display the numbers in three TextBoxes respectively
                     switch(i)
                     {
                         case 0:
                             textBox1.Text = randomNumber.ToString();
                             break;
                         case 1:
                             textBox2.Text = randomNumber.ToString();
                             break;
                         case 2:
                             textBox3.Text = randomNumber.ToString();
                             break;
                     }
                 }
             }
         }
    }
    
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful