Question

I am struggling with the databinding syntax here. For example I have a data structure like this -

public class Course{

public string CourseName {get;set;}

public string CourseCode {get;set;}

public List<Instructor> InstructorsTeaching{get;set;}

}

public class Instructor{

public string InstructorName{get;set;}

public string InstructorCode{get;set;}

}

Now if I want to bind this List Courses to say a gridview manually, I could do

<asp:TextBox runat="server" ID="tbCourseName" Text='<%# Bind("CourseName")%>'/>

while specifying for edit template of the grid but how do I bind the Instructors teaching property to say a ListBox in the same row, I cant figure out the syntax , here is an exaple of what I tried and failed

<asp:ListBox runat="server" ID="tbInstructors" 
     DataSource='<%# Eval("InstructorsTeaching") as List<Instructor> %>'>
    <asp:ListItem Text='<%# Bind("InstructorCode")%>' 
                 Value='<%# Bind("InstructorName")%>'/>...
 <as:ListBox/>

My above code does not work for sure :). Ideally I would like to do this in markup instead of code behind.

Was it helpful?

Solution

I don't think you can set a datasource like that, try setting it on GridView's RowDataBound event

OTHER TIPS

You've hit on a major reason that ASP.NET 2-way databinding sucks: You really can't do nested 2-way data-binding.

For one thing, although you can do it with Eval, ASP.NET doesn't allow nested graph syntax with the Bind expression, (i.e. <%# Bind("Customer.FirstName") %>).

Beyond that, for nested list controls like your scenario, each list will require an additional DataSource control. You are setting the DataSource on your ListBox, which will work for Eval expressions, but for binding expressions to work, you must use DataSourceID to provide the ID of a DataSource control that provides the inner result set. And even then your results would be kludgy since you could only update one datasource at a time.

2-way databinding was probably written with SqlDataSource in mind and not ObjectDataSource. If you have a multi-level object graph, you'll find it painful to use 2-way databinding.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top