[英]How to retrieve data RANDOMLY from SQL Server using C#
我的數據庫中有一組問題,每次都需要以隨機順序檢索它們。
有人可以幫我解決 C# 代碼嗎? 我正在使用 Visual Studio 2012。
提前致謝。
這是我目前使用的代碼:
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;
public partial class perform_test : System.Web.UI.Page
{
public int CurrentPage
{
get
{
object o = this.ViewState["_CurrentPage"];
if (o == null)
return 0;
else
return (int)o;
}
set
{
this.ViewState["_CurrentPage"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
//Response.Write(Session["Company"]);
if (!Page.IsPostBack)
{
Session.Add("CorrectAnswers", 0);
//Session.Add("Questions", 0);
Session.Add("Answer", "");
}
if (repeat_exam_data.Controls.Count > 0)
{
for (int i = 1; i <= 4; i++)
{
RadioButton rad = repeat_exam_data.Controls[0].FindControl("Choice" + i.ToString()) as RadioButton;
if (rad.Checked)
{
Session["Answer"] = rad.Text;
break;
}
}
}
GetPage();
}
protected void GetPage()
{
DataTable exam_data = new DataTable();
exam_data = BussinessLayer.GetExamData(Session["Company"].ToString(), Session["Subject"].ToString(), Session["ExamId"].ToString());
PagedDataSource pgds = new PagedDataSource();
pgds.DataSource = exam_data.DefaultView;
pgds.AllowPaging = true;
pgds.PageSize = 1;
pgds.CurrentPageIndex = CurrentPage;
repeat_exam_data.DataSource = pgds;
repeat_exam_data.DataBind();
Cmd_Next.Enabled = !pgds.IsLastPage;
Cmd_Finish.Enabled = pgds.IsLastPage;
lblQno.Text = Convert.ToString((CurrentPage + 1));
lblCorrectAnswers.Text = Session["CorrectAnswers"].ToString();
}
protected void Cmd_Next_Click(object sender, EventArgs e)
{
CalculateMark();
CurrentPage += 1;
GetPage();
}
protected void Cmd_Finish_Click(object sender, EventArgs e)
{
CalculateMark();
string strSql = "INSERT INTO tbl_result(ExamId,StudentId,Mark) VALUES('" + Session["ExamId"] + "','" + Session["uname"] + "','" + Session["CorrectAnswers"] + "')";
BussinessLayer.PutData(strSql);
Response.Redirect("~/canexamresult.aspx");
}
private void CalculateMark()
{
HiddenField ans = repeat_exam_data.Controls[0].FindControl("Answer") as HiddenField;
if (Session["Answer"].ToString() == ans.Value)
Session["CorrectAnswers"] = (int)Session["CorrectAnswers"] + 1;
}
}
此代碼不包含負責獲取數據的代碼。 它可能在 BussinessLayer.GetExamData() 內。 例如,您可以使用
ORDER BY NEWID()
在查詢結束時。
您可以使用
ORDER BY NEWID();
正如 Sleipneir 建議的那樣,或者將整個數據集加載到一個列表中,然后以隨機方式吃掉該列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.