简体   繁体   English

添加控件时如何将控件随机化

[英]How can I randomize controls when they are added

I have three ul like this : 我有三个这样的ul:

<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 . 怎么做那样的事情。

You could put those ul in an array 您可以将这些ul放在一个数组中

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. 请注意,您不需要uls.Length - 1因为在Next方法中上限是互斥的。

如果要随机化ul的内容,则可以简单地使用颜色的int值作为随机定义。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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