dimanche 25 mars 2018

Index was outside the bounds of the array when use random c#

I create a question pool from where I choose random question to apply some algorithm, anyway when I debug the program I get Index was outside the bounds of the array error.

to have a clear idea about what I am talking about, here is my class for question:

Firstly I define class Gene represent question

public class Gene
{
    public string question { get; set; }
    public string CLO { get; set; }
    public string type { get; set; }
    public string Answer { get; set; }
    public string mark { get; set; }
    public string chapter { get; set; }
    public Gene(string s, string t, string i, string a, string m, string c)
    {
        this.question = s;
        this.type = t;
        this.CLO = i;
        this.Answer = a;
        this.mark = m;
        this.chapter = c;

    }
}
List<Gene> QuestionList = new List<Gene>();

then I bring question from database

protected void DropDownList5_SelectedIndexChanged(object sender, EventArgs e)
{
    string sub = DropDownList5.Text;


    SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Sondos\Downloads\For the project\suz\ExamGenerationSystem.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
    string s = "select * FROM QuestionBank WHERE (Cource_Code = '" + DropDownList5.SelectedItem.Text + "') ORDER BY RAND()";
        SqlCommand cmd = new SqlCommand(s, con);
        SqlDataReader dr;
        con.Open();
        dr = cmd.ExecuteReader();
        dr.Read();
        while (dr.Read())
        {
            string ques = dr["Question"].ToString();
            string questype = dr["Question_Type"].ToString();
            string quesCLO = dr["CLO"].ToString();
            string quesAnswer = dr["Answer"].ToString();
            string quesMark = dr["Mark"].ToString();
            string quesChapter = dr["Chapter"].ToString();
            QuestionList.Add(new Gene(ques, questype, quesCLO, quesAnswer, quesMark, quesChapter)); 
        }
}

then I make the question Pool

 Gene[] QuestionPool { get { return QuestionList.ToArray(); } }

and when I try to choose question randomly using this :

private System.Random randome;
     private Gene GetRandomQuestion()
            {
                int i = randome.Next(QuestionPool.Length);
                return QuestionPool[i];
            }

the error Index was outside the bounds of the array was in line

 return QuestionPool[i];




Aucun commentaire:

Enregistrer un commentaire