Search code examples
asp.netrepeaterbindobjectdatasource

ASP.NET ObjectDataSource Binding Automatically to Repeater - Possible?


I have a Question class:

class Question {
    public int QuestionNumber { get; set; }
    public string Question { get; set; }
    public string Answer { get; set; }
}

Now I make an ICollection of these available through an ObjectDataSource, and display them using a Repeater bound to the DataSource. I use <%#Eval("Question")%> to display the Question, and I use a TextBox and <%#Bind("Answer")%> to accept an answer.

If my ObjectDataSource returns three Question objects, then my Repeater displays the three questions with a TextBox following each question for the user to provide an answer.

So far it works great.

Now I want to take the user's response and put it back into the relevant Question classes, which I will then persist.

Surely the framework should take care of all of this for me? I've used the Bind method, I've specified a DataSourceID, I've specified an Update method in my ObjectDataSource class, but there seems no way to actually kickstart the whole thing.

I tried adding a Command button and in the code behind calling MyDataSource.Update(), but it attempts to call my Update method with no parameters, rather than the Question parameter it expects.

Surely there's an easy way to achieve all of this with little or no codebehind?

It seems like all the bits are there, but there's some glue missing to stick them all together.

Help!

Anthony


Solution

  • You have to handle the postback event (button click or whatever) then enumerate the repeater items like this:

    foreach(RepeaterItem item in rptQuestions.Items)
    {
       //pull out question
       var question = (Question)item.DataItem;
       question.Answer = ((TextBox)item.FindControl("txtAnswer")).Text;
    
       question.Save() ?  <--- not sure what you want to do with it
    }