检查代码并向我建议解决方案
问题描述:
SqlConnection con = new SqlConnection(@"Data Source=ATTRIS-3BC2A6\SQLEXPRESS;Initial Catalog=harsha;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("select * from Exam", con);
da.Fill(ds, "Exam");
dt = ds.Tables["Exam"];
i = dt.Rows.Count;
int k = 0;
dr = dt.Rows[k];
Label1.Text = dr[0].ToString();
RadioButton1.Text = dr[1].ToString();
RadioButton2.Text = dr[2].ToString();
RadioButton3.Text = dr[3].ToString();
RadioButton4.Text = dr[4].ToString();
我有10个问题.每次运行应用程序时,我都应该获得随机模式.
因此,我应该在查询中进行哪些更改才能每次都得到一个随机问题.
I have 10 questions.every time i should get random pattern when the application runs.
so what changes i should make in the query to get a random question each time.
答
使用Random类:
Use the Random class:
private Random rand = new Random;
...
int numberOfQuestions = 10;
int rowIndex = rand.Next(numberOfQuestions);
dr = dt.Rows[rowIndex];
但是我可能会将numberOfQuestions设置为数据表的行数,而不是将其固定为10.
But I would probably set numberOfQuestions to the data table row count, rather than fixing it at ten.
For 1 record
SELECT TOP 1 * FROM Exam ORDER BY NEWID()
For 4 Record
For 4 Record
SELECT TOP 4 * FROM Exam ORDER BY NEWID()
您可以使用SQL Select Query从数据库中选择一个随机问题
这是示例
You can select a random Question from database using SQL Select Query
here is example
SELECT * FROM table ORDER BY RAND() LIMIT 1