tmutton
tmutton

Reputation: 1101

Randomize control visibility (asp.net)

I have been searching for a solution to this but haven't come across one yet and i'm not too good at randomizing with c#.

I have three asp.net controls and I would like to make visible one of those controls at any one time.

The controls may be like this

panel 1

panel 2

panel 3

So I guess all of these controls would be set to visible='false' by default. Then the randomize method would choose one of those controls and make it visible='true'.

I think the hardest part here would be to put the controls into an array to randomize? Again, i'm not sure how to do that so any help would be great.

Thank you in advance.

Upvotes: 1

Views: 274

Answers (2)

sinni800
sinni800

Reputation: 1449

How about this:

Panel[] array1 = new Panel[3];
array1[0] = panel1;
array1[1] = panel2;
array1[2] = panel3;

foreach(Panel p in array1) {
  p.Visible = False;
}

Random rand = new Random();
int toshow = rand.next(0, 3);
array1[toshow].Visible = true;

This was conveiced from my head without any IDE to support if it works correctly. The Class name for random might be wrong (isn't it in the Math Namespace?)

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460238

Random rnd = new Random();
var visiblePanel = rnd.Next(1, 4);
switch (visiblePanel) {
    case 1:
        Panel1.Visible = true;
        Panel2.Visible = false;
        Panel3.Visible = false;
        break;
    case 2:
        Panel1.Visible = false;
        Panel2.Visible = true;
        Panel3.Visible = false;
        break;
    case 3:
        Panel1.Visible = false;
        Panel2.Visible = false;
        Panel3.Visible = true;
        break;
}

Upvotes: 1

Related Questions