Laziale
Laziale

Reputation: 8225

randomize display order for controls in asp.net

I would like to know how I can randomize the order in which some controls are displayed. Basically, I have 5 hyperlinks, and I want on each load the order in which they are displayed to be randomized. Which way I can accomplish that? Thanks, Laziale

Upvotes: 0

Views: 469

Answers (1)

Peter
Peter

Reputation: 9712

Assuming all 5 links are in an asp panel named "pnlLinks", and that the links are the only controls in the panel:

    <asp:Panel ID="pnlLinks" runat="server">
        <asp:HyperLink ID="HyperLink0" runat="server" Text="test1" />
        <asp:HyperLink ID="HyperLink1" runat="server" Text="test2" />
        <asp:HyperLink ID="HyperLink2" runat="server" Text="test3" />
        <asp:HyperLink ID="HyperLink3" runat="server" Text="test4" />
        <asp:HyperLink ID="HyperLink4" runat="server" Text="test5" />
    </asp:Panel>

Use code like this to randomize their order:

protected void Page_Load(object sender, EventArgs e)
{
    var ctrls = new List<Control>();

    foreach (Control c in pnlLinks.Controls)
    {
        ctrls.Add(c);
    }

    Random rand = new Random();
    //randomize and put back in
    foreach (Control c in ctrls.OrderBy(c => rand.Next()))
    {
        pnlLinks.Controls.Remove(c);
        pnlLinks.Controls.Add(c);
    }
}

Upvotes: 1

Related Questions