Good day everyone,
so here, I have a problem with my repeater control’s SQL query, what I would really want to happen, is I have a randomized number from 1 to 60, that will tell the database which test question to select, (if it’s only one, it’s not a problem, haha.) but then, I am required to display 20 questions from my database to the repeater control. my database also holds the 60 questions. So yeah, I tried some solutions in the net, but then my code always returns only one record, and it’s quite a pain. Hope somebody could help me, I know to some it’s quite basic, but I’m only a budding programmer, so yeah, thanks in advance.
btw, this is the chunk of code,
protected void Page_Load(object sender, EventArgs e)
{
int i = 1;
Random r = new Random();
while (i <= 20)
{
int iss;
string constr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mark\Desktop\thesis\WebSite8\App_Data\thesisDB.mdf;Integrated Security=True;User Instance=True";
SqlConnection con = new SqlConnection(constr);
string com = "SELECT * from CHAP1_quiz WHERE questionnumber = @num";
SqlDataAdapter comms = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand(com, con);
iss = r.Next(1, 60);
comms.SelectCommand = cmd;
cmd.Parameters.Add("@num");
DataSet ds = new DataSet();
con.Open();
comms.Fill(ds);
Repeater1.DataSource = ds;
Repeater1.DataBind();
i++;;
con.Close();
}
}
oh yeah, let me tell you, when i run this code, it only displays 1 record. But I need 20, I know it’s a lame question, but it’s been bugging me for quite a while.
Your code would be in round trip 20 times in database, because each while loop you select one question, try to create
new DataSetand bind data source again. That’s why your list has just one question.To avoid the round trip to database, instead of using random number and
whileloop in code, , get rid ofwhileloop, you can useSELECTrandom in SQL byORDER BY NEWID()