Home » CodeDigest


How to shuffle my data values displayed in DataGrid - A Step Ahead Series
Submitted By Gaurav Arora
On 3/6/2009 5:44:25 AM


Need to shuffle my results everytime when user clicks the button.


We can do the same in a tricky way, the Sql newid() function plays a great role in this context.


The following piece of code tells the whole story:

Design page [shuffleresults.aspx]

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="shuffleresults.aspx.cs" Inherits="shuffleresults" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="">

<head id="Head1" runat="server">

<title>How to Shuffle Result-Sets</title>



<form id="form1" runat="server">


<asp:DataGrid ID="dgEmp" runat="server" AlternatingItemStyle-BackColor="AliceBlue">

<AlternatingItemStyle BackColor="AliceBlue" />



<br />


<asp:Button ID="btnShuffle" runat="server" ToolTip="Click to Shuffle Resuts" Text="Shuffle-Results"

OnClick="btnShuffle_Click" />

<asp:Button ID="btnNormal" runat="server" ToolTip="Click to Check Normal Result"

Text="Normal Results" OnClick="btnNormal_Click" />





Code-Behind page [shuffleresults.aspx.cs]

/* This Example is a part of different

* * examples shown in Book:

* * C#2005 Beginners: A Step Ahead

* * Written by: Gaurav Arora

* * Reach at : */

#region Code Region

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

public partial class shuffleresults : System.Web.UI.Page


protected void Page_Load(object sender, EventArgs e)


if (!IsPostBack)





void BindData(string strFldName)


SqlConnection myCon = new SqlConnection("Server=(local);uid=sa;pwd=;database=hrnpayroll");

SqlCommand myCmd = new SqlCommand("Select Top 10 * from Employees order by " + strFldName, myCon);


SqlDataReader myDr = myCmd.ExecuteReader();

dgEmp.DataSource = myDr;





protected void btnShuffle_Click(object sender, EventArgs e)


//Here just pass the newid() function to shuffle the output and see the magic



protected void btnNormal_Click(object sender, EventArgs e)


//reset the dataresult




#endregion Code Region

Step(s) to test above:

  1. Copy/Paste above both design and code-behind file(s)
  2. Name it as mentioned
  3. Build the project
  4. Run the project
  5. Click the Shuffle-Button

Check the output.

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..