将按钮分配为仅显示一个随机标签

时间:2017-10-23 04:31:36

标签: c# arrays wpf random labels

我创建了一个标签数组,只需单击按钮即可看到,但由于我有许多按钮,我想指定一个按钮,只显示一个标签 我在制作一个可以看到多个标签的按钮时遇到了麻烦

这是我使用的代码:

var labels = Controls.OfType<Label>().ToArray();
//And then randomly make on of them visible.
var random = new Random();
var label = labels[random.Next(0, labels.Count - 1)];
label.Visible = true;

1 个答案:

答案 0 :(得分:0)

在Winforms中,您只需声明一个私有Random变量,然后在其中一个按钮的Click事件中,您可以选择一个在标签数组的有效索引范围内的随机数,像:

private Label[] labels = new Label[10];  // Presumably this array is filled somewhere
private Random rnd = new Random();

private void Form1_Load(object sender, EventArgs e)
{
    for(int i = 0; i < labels.Length; i++)
    {
        labels[i] = new Label
        {
            Height = 20,
            Left = 10,
            Name = $"Label{i}",
            Tag = i,
            Text = $"Label{i}",
            Top = 10 + 20 * i,
            Visible = false
        };

        this.Controls.Add(labels[i]);
    }
}

private void button1_Click(object sender, EventArgs e)
{
    if (labels != null && labels.Length > 0)
    {
        // If needed, this will hide any currently visible labels in the array
        foreach(var label in labels.Where(label => label != null && label.Visible))
        {
            label.Visible = false;
        }

        // Pick a random label and make it visible
        labels[rnd.Next(0, labels.Length)].Visible = true;
    }
}