Shuffle the position of button controls on a page using an array and the random function

Category VB.Net Sub Category Utilities Bespoke
Bookmark and Share
The purpose of this is to make a series of controls (in this case buttons) randomly appear on the page. Each button is still related to the same event but their position and caption text is changed to keep the same physical order e.g. A, B, C, D, E.
This is very useful in situations where you want to mix up buttons that are linked to questions in a test, so that the person taking the test cannot rely on the order of butons to help work out the answers. In the case where someone who has already taken the test, has told them the order to expect the answers.

In the aspx page:

Copy Code
<div style="position:relative;"> <asp:Button ID="btn1" runat="server" Text="1" ToolTip="1 orig" /> <asp:Button ID="btn2" runat="server" Text="2" ToolTip="2 orig" /> <asp:Button ID="btn3" runat="server" Text="3" ToolTip="3 orig" /> <asp:Button ID="btn4" runat="server" Text="4" ToolTip="4 orig" /> <asp:Button ID="btn5" runat="server" Text="5" ToolTip="5 orig" /> </div>


In the aspx.vb code behind page:

Copy Code
Private btnHoriPos() As String = {"50", "100", "150", "200", "250"} Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load shuffleButtons() End Sub Private Sub shuffleButtons() shuffle(btnHoriPos, 7) For i As Int32 = 1 To 5 Dim btn As Button = DirectCast(FindControl(String.Concat("btn", i)), Button) 'set the button positions based on shuffle btn.Attributes.Add("Style", String.Format("position:absolute; left:{0}px;", btnHoriPos(i - 1))) 'set the text to be correct again after move fixButtonText(btn, btnHoriPos(i - 1)) Next End Sub Private Sub shuffle(ByRef arrayToBeShuffled As Array, ByVal numberOfTimesToShuffle As Integer) Dim rndPosition As New Random(DateTime.Now.Millisecond) For i As Integer = 1 To numberOfTimesToShuffle For i2 As Integer = 1 To arrayToBeShuffled.Length swap(arrayToBeShuffled(rndPosition.Next(0, arrayToBeShuffled.Length)), arrayToBeShuffled(rndPosition.Next(0, arrayToBeShuffled.Length))) Next i2 Next i End Sub Private Sub swap(ByRef arg1 As Object, ByRef arg2 As Object) Dim strTemp As String strTemp = arg1 arg1 = arg2 arg2 = strTemp End Sub Private Sub fixButtonText(ByRef btn As Button, ByVal position As Int32) '{"50", "100", "150", "200", "250"} Select Case position Case 50 btn.Text = "A" Case 100 btn.Text = "B" Case 150 btn.Text = "C" Case 200 btn.Text = "D" Case 250 btn.Text = "E" End Select End Sub
Share the love
Bookmark and Share