Anyname Donotcare
Anyname Donotcare

Reputation: 11423

How can I randomize controls when they are added

I have three ul like this :

<ul id="column3" class="column" runat="server"> </ul>

<ul id="column4" class="column" runat="server"> </ul>


<ul id="column5" class="column" runat="server"> </ul>

I wanna to add listitems to them randomly:

 HtmlGenericControl listItem1 = new HtmlGenericControl("li");
 listItem1.Attributes.Add("class", colors[RandString.Next(0, colors.Length -1)]);
 column3.Controls.Add(listItem1); //here  i wanna to randomize the ul(column3,column4,column5) like i do with the colors

How to do something like that .

Upvotes: 0

Views: 62

Answers (3)

Phillip Ngan
Phillip Ngan

Reputation: 16126

var lists = new [] { column3, column4, column5 };
Random rand = new Random();
for ( int n = 0; n < 10; n++ )
{
   HtmlGenericControl listItem1 = new HtmlGenericControl("li");
   listItem1.Attributes.Add("class", colors[RandString.Next(0, colors.Length -1)]);
   lists[rand.Next(0,lists.Count)].Controls.Add(listItem1);
}

Upvotes: 1

Shimmy Weitzhandler
Shimmy Weitzhandler

Reputation: 104781

If you mean randomize the ul's content, you could simply use the color's int value as the random definition.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039298

You could put those ul in an array

var uls = new[] { column3, column4, column5 };

and then pick a random one:

var ul = uls[random.Next(0, uls.Length)];
ul.Controls.Add(listItem1);

Notice that you don't need uls.Length - 1 because the upper bound is exclusive in the Next method.

Upvotes: 2

Related Questions