Search code examples
c#asp.netlinq-to-sqlrepeaterasp.net-controls

How would i add this to a repeater?


Morning,

I am writing a simple quiz app. I am getting my questions and answers from the my MS SQL DB. How would i go about getting this and putting it into say a repeater control, so i can display 6 questions, with their answers.

Or... do you know of a better way to do this?

 var questions = dc.Questions.ToList().OrderBy(q => Guid.NewGuid()).Take(6);

        foreach (var q in questions)
        {
            litQuestion.Text = q.question1;
            int qId = q.id;

            var ans = dc.Answers.Where(a => a.questionId == qId).ToList();

            litAnswer1.Text = ans[0].answer1.ToString();
            litAnswer2.Text = ans[1].answer1.ToString();
            litAnswer3.Text = ans[2].answer1.ToString();
        }

dc is my datacontext.

Thanks in advance.


Solution

  • Besides the other answers, this is a really simple way to do it:

    Assuming your Question object contains a collection of available answers called Answers

    <asp:Repeater runat="server" DataSourceID="ods">
        <ItemTemplate>
            <%# Eval("QuestionText") %>
            <br />
            <asp:RadioButtonList runat="server" DataSource='<%# Eval("Answers") %>' DataTextField="AnswerText" DataValueField="ID">
            </asp:RadioButtonList>
        </ItemTemplate>
    </asp:Repeater>
    

    Which produces something like:

    enter image description here

    Edit 1

    The ods DataSource:

        <asp:ObjectDataSource ID="ods" runat="server" 
            SelectMethod="GetQuestions" 
            TypeName="WebApplication1.Questions.QuestionsContext">
        </asp:ObjectDataSource>
    
        public IEnumerable<Question> GetQuestions()
        {
            // return your questions
        }
    
    public class Question
    {
        public Guid ID { get; set; }
        public string QuestionText { get; set; }
        public IEnumerable<Answer> Answers { get; set; }
        public bool MultipleAnswers { get; set; }
        public bool IsCorrect { get; set; }
    
        public Question()
        {
            this.Answers = Enumerable.Empty<Answer>();
        }
    }
    public class Answer
    {
        public Guid ID { get; set; }
        public Question Question { get; set; }
        public bool IsCorrect { get; set; }
        public string AnswerText { get; set; }
        public bool WasSelected { get; set; }
    }