Problem:
Need to shuffle my results everytime when user clicks the button.
Solution:
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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
< html xmlns="http://www.w3.org/1999/xhtml">
< head id="Head1" runat="server">
<title>How to Shuffle Result-Sets</title>
</ head>
< body>
<form id="form1" runat="server">
<div>
<asp:DataGrid ID="dgEmp" runat="server" AlternatingItemStyle-BackColor="AliceBlue">
<AlternatingItemStyle BackColor="AliceBlue" />
</asp:DataGrid>
</div>
<br />
<div>
<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" />
</div>
</form>
</ body>
</ html>
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 : http://MsDotNetHeaven.com */
#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)
{
BindData( "ID");
}
}
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);
myCon.Open();
SqlDataReader myDr = myCmd.ExecuteReader();
dgEmp.DataSource = myDr;
dgEmp.DataBind();
myDr.Close();
myCon.Close();
}
protected void btnShuffle_Click(object sender, EventArgs e)
{
//Here just pass the newid() function to shuffle the output and see the magic
BindData( "newid()");
}
protected void btnNormal_Click(object sender, EventArgs e)
{
//reset the dataresult
BindData( "id");
}
}
#endregion Code Region
Step(s) to test above:
- Copy/Paste above both design and code-behind file(s)
- Name it as mentioned
- Build the project
- Run the project
- Click the Shuffle-Button
Check the output.
|