简体   繁体   中英

Passing a value of an array to button C# WinForm

I know about arrays. But I only know it using console, now I don't know how to implement it in windows form using visual studio, and I cannot saw anything online about what I wan't to do. Let's say for example I initialise an array of int:

int[] n = new int[5] {1, 2, 3, 4, 5};

Now what I want is, for example, there are 5 buttons, let's say when I click on button1, it will output:

MessageBox.Show("Number " + ... // random value in an array n

The same will happen to other 5 buttons but with no repetition. I know my question can be flagged as inappropriate but, I am asking this question since yesterday, an took a research the whole night but still nothing.

So you need to grab a random value from the array, then remove that value so that the other buttons can not show the same number. A List<int> would be easier to work with.

private void formLoad(object sender, EventArgs e) {  
    // wire this handler up to your Form.Load event

    List<int> numbers = new List<int>() {101,22,373,414,625};
    Random random = new Random();

    Button1.Click += clickHandler;
    Button2.Click += clickHandler;
    Button3.Click += clickHandler;
    Button4.Click += clickHandler;
    Button5.Click += clickHandler;
}

private void clickHandler(object sender, EventArgs e) {
    if (0 == numbers.Count) { 
        MessageBox.Show("There are no more numbers in the list.");
        return;
    }
    int index = random.Next(0, numbers.Count);
    MessageBox.Show("Number " + numbers[index].ToString());
    numbers.RemoveAt(index);
}

I would like to suggest Sam Axe's solution. it is very simple and easy to understand. The only reason to provide this solution is if you want to maintain the selected item history then this solution might be helpful for you.

You can stored the used value in a list which can be checked while next random number is being fetched.

To get the random integer number. You can use Random.Next(int32, int32) method of Random class.

int[] n = new int[5] {1, 2, 3, 4, 5};
List<int> usedN = new List<int>();
Random rnd = new Random();

private void button1_click(object sender, EventArgs e)
{        
    int iIndex = rnd.Next(0, n.Length-1);
    int iRnd = n[iIndex];

    if (usedN.Count == n.Length)
        return;

    usedN.Add(iRnd);
    MessageBox.Show("Number " + iRnd.ToString());
}

This answer has similarities to Sam Axe's answer, but was created independently. It may help someone. Code is available on https://github.com/zedfoxus/StackOverflow29203245

The form has 5 buttons and an extra button to reset the numbers after they are all used up.

Form1.cs

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace StackOverflow29203245
{
    public partial class Form1 : Form
    {
        private readonly List<int> _numbers  = new List<int> {1, 2, 3, 4, 5};
        private readonly List<int> _asked = new List<int>();

        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Select random integer from the list of integers. If no numbers are left, throw an exception
        /// </summary>
        /// <returns>Random integer from the list</returns>
        private int RandomInteger()
        {
            if (_numbers.Count == 0)
            {
                throw new Exception("All numbers have been selected");
            }

            var random = new Random();
            var index = random.Next(_numbers.Count);
            var selectedNumber = _numbers[index];
            _asked.Add(selectedNumber);
            _numbers.Remove(selectedNumber);
            return selectedNumber;
        }


        /// <summary>
        /// Show the message box. If all numbers are selected, show appropriate message
        /// </summary>
        private void ShowMessage(object sender, EventArgs e)
        {
            try
            {
                MessageBox.Show(@"Number " + RandomInteger());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        /// <summary>
        /// Reset numbers
        /// </summary>
        private void button6_Click(object sender, EventArgs e)
        {
            _numbers.AddRange(_asked);
            _asked.Clear();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM