我的数据库中有一组问题,每次都需要以随机顺序检索它们。
有人可以帮我解决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;
}
}
答案 0 :(得分:1)
此代码包含负责支持数据的代码。它在里面 BussinessLayer.GetExamData()可能。 例如,您可以使用
来实现随机订单ORDER BY NEWID()
在查询结束时。
答案 1 :(得分:0)
您可以使用
ORDER BY NEWID();
正如Sleipneir建议的那样,或者将整个数据集加载到一个列表中,并以随机方式吃掉该列表。