Displaying Random Record

80酷酷网    80kuku.com

  domSystem namespace has a Random class which is used for generating random numbers. This article explains how to display a random record from a database table using the random class.

The Random class has an overloaded method named Next which will generate random numbers. One variant of this Next method takes in the minimum and maximum numbers and generates random number within the range. For example:

Random R = new Random();
Random.Next(1,100);


will generate a random number between 1 and 100.

To display a random record from the database we will pass the maximum value for the id column and minimum value for the id column to the Next method and generate a random number.

int RecNo=0,MaxRecNo,MinRecNo;
Random R =  new Random();
SqlDataReader DR;
SqlConnection CN = new SqlConnection("Server=YourServerName;DataBase=NorthWind;UID=SA;");
CN.Open();
SqlCommand Cmd = new SqlCommand("select Max(ProductId) as MaxProdid ,Min(ProductId) as MinProdId  from Products",CN);
DR= Cmd.ExecuteReader();
DR.Read();
MaxRecNo = (int)DR["MaxProdid"]  ;
MinRecNo = (int)DR["MinProdid"]  ;
RecNo = R.Next(MinRecNo,MaxRecNo);


Then we will fetch the the record whose id is equal to the random number generated.

Cmd = new SqlCommand("select * from Products Where ProductID = " + RecNo,CN);
DR = Cmd.ExecuteReader();
DR.Read();
Response.Write("Product Of The Day <b>" + DR["ProductName"] + "</b>");
CN.Close();

分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: