开发者

How to Randomly Set Initial Index Declaratively or in Code?

I have a DropDownList and want to randomly set the selected index at PageLoad. Can this be done declaratively in the aspx file?

If so, how? If not, how do I do so in PageLoad() in C#?

Tha开发者_高级运维nks.


It s possible...

You may use the following code lines in Page_Load event's event handler:

Random r = new Random();
int nextIndex = r.Next(0, dropDownList1.Items.Count);
dropDownList1.SelectedIndex = nextIndex;

Hope this helps...


On aspx you would have you use a script. Just do it on PageLoad, seems cleaner.

Javascript code is this:

var ddl = document.getElementById('ddlList');
ddl.options[Math.floor(Math.random()*(ddl.options.length+1))].selected = true;

http://jsfiddle.net/SN47U/


no idea how to do this in the aspx... but on PageLoad you just do this:

myDropDownList.SelectedIndex = new System.Random().Next (myDropDownList.Items.Count);


No, its possible only in Page_Load

        var rnd = new Random();
        listBox1.SelectedIndex = rnd.Next(listBox1.Items.Count);


you can try the following:

protected void Page_Load(object sender, EventArgs e)
{
    int index = new Random().Next(0,DropDownList1.Items.Count);
    DropDownList1.SelectedIndex = index;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜