How to bind GridView's DataSource to an object's List<T> property??

Hi all, I really hope someone has a solution for this.

I'm using ObjectDataSource throughout my project. I have an Order class which has, among other properties, a List<Product> ProductList property and a GetProductList method.

I use GridView template field to present a list of Orders. For each column, I can, for example, bind a textbox to the OrderID property of my underlying Order object. I can achieve this by simply clicking the textbox's datbindings and associate the Text property to the exposed OrderID field in the underlying Order object. This works fine.

I now embed a second GridView inside the first GridView's Tamplate field which must display a list of products for this order. Essentially to make a Master/Details scenario. Using the same logic as with the textbox, I edit the embedded GridView's databindings. One of the Bindable properties is DataSource. I bind DataSource with the underlying Order object's exposed ProductList property (of type List<Product>, thinking this will "feed" the GridView. It does not. I get this error message:

 Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.

Here's what I'm trying for:

<asp:GridView ID="gvOrderList" runat="server" DataKeyNames="OrderId" DataSourceID="odsOrderList" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label55" runat="server"
Text='<%# Eval("OrderId") %>'></asp:Label>

<asp:GridView ID="gvProductList" runat="server"
DataSource='<%# Eval("ProductList") %>'>
<Columns>
...
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

In stead, I must resort to using another embedded ObjectDataSource for the embedded GridView and binding the two on the RowDataBound event of the Orders grid like this:

  

protected void gvOrderList_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Order x = (Order)e.Row.DataItem;
        _OrderManager = new OrderManager(x);
        GridView gv = (GridView)e.Row.FindControl("gvProductList");
        gv.DataBind();
    }
}

THEN

protected void odsProductList_ObjectCreating(object sender, ObjectDataSourceEventArgs e) {

e.ObjectInstance = OrderManager;

}

THEN

<asp:GridView ID="gvProductList" runat="server" DataSourceID="odsProductList" >....</asp:GridView>
<asp:ObjectDataSource ID="odsProductList" runat="server" DataObjectTypeName="SalesTracker.BusinessLogicLayer.Product"
DeleteMethod="RemoveProduct" InsertMethod="AddProduct" OnObjectCreating="odsProductList_ObjectCreating"
SelectMethod="GetProductList" TypeName="SalesTracker.BusinessLogicLayer.OrderManager"
UpdateMethod="EditProduct"></asp:ObjectDataSource>
 

Evidently much less elegant than the first alternative.

How can I bind a GridView DataSource property to an object's List<T> property?

 

Thanks in advance

 

0
signmeup911
12/11/2008 4:19:19 PM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

3 Replies
1140 Views

Similar Articles

[PageSpeed] 54

System.Collections.Generic.List<Employee> emp = new System.Collections.Generic.List<Employee>();

        emp.Add(new Employee("Jack", 22, "Marketing"));
        emp.Add(new Employee("Anna", 28, "Advertising"));
        emp.Add(new Employee("Linra", 23, "Advertising"));
        emp.Add(new Employee("Jacob", 44, "Production"));
        emp.Add(new Employee("Zinger", 28, "PPC"));
 
        GridView1.DataSource = emp;
        GridView1.DataBind();

 

Check out Tip 10 over here: http://www.dotnetcurry.com/ShowArticle.aspx?ID=156

 


ASP.NET Grid With Excel Capabilities | 27 GridView Tips & Tricks | Hosting your site? | SQL Server Tips
0
Suprotim
12/11/2008 5:03:44 PM

 Thanks for the quick reply, but this solution is not quite what I'm looking for as the GridView in your solution is not bount the an ObjectDataSource control, but rather to a List<T>.

However, the solution you provide does complement my question. If you can bind the grid like this:

 GridView1.DataSource = emp; //Where emp is a List<T>.

why can you not bind like this?

<asp:GridView ID="gvProductList" runat="server" 
DataSource='<%# Eval("ProductList") %>'> <!-- Where ProductList is also a List<T>. -->
Someone else has apparently implemented this, without receiving the error described in my original post. Find the post here.
 Thanks again 

 

0
signmeup911
12/14/2008 4:04:42 PM

Hmm, thats pretty weird, it works fine for me. See the example below:

<asp:LinqDataSource ID="categoriesSource"

    runat="server"

    ContextTypeName="FowlerSamples.NorthwindDataContext"

    TableName="Categories">

 </asp:LinqDataSource>

<asp:GridView ID="GridView1" runat="server"

    AutoGenerateColumns="False"

    DataKeyNames="CategoryID"

    DataSourceID="categoriesSource">

    <Columns>           

        <asp:TemplateField>

            <ItemTemplate>

                <asp:GridView runat="server" DataSource='<%# Eval("Products") %>'>

                </asp:GridView>

            </ItemTemplate>                   

        </asp:TemplateField>

    </Columns>

</asp:GridView>

It may be worth your while to take a look at the generated code and see if you can figure out whats going on. Take a look at my blog post and you can see how to do this.
There is a good explaination on what is happening here:
http://aspadvice.com/blogs/joteke/archive/2008/08/24/Is-_2200_Databinding-methods-such-as-Eval_280029002C00_-XPath_280029002C00_-and-Bind_28002900_-can-only-be-used-in-the-context-of-a-databound-control_2E002200_-causing-you-grief_3F00_.aspx


David Fowler
SDE, ASP.NET Team, Microsoft
0
davidfowl
12/14/2008 7:40:18 PM
Reply:

Similar Artilces:

Label control's text doesn't appear to be set (in the page which has a user control )when trying to update the text property in the FormView's ItemUpdated event
Hi There,I have a user control which hosts a formview control, gridview control and a label control. The grid view is usedto show rows in the DB and when clicked to edit each row, a form view opens up in edit mode with that particular row info. So I have nothing in the item template.My first question is..is it mandatory to have smth in the itemtemplate of the form view.I have controls in edititemtemplate and insertitemtemplate.When a particular row is edited, I would like to show a status msg showing that the row has been updated.For this, I use the ItemUpdated event of the formview and try ...

Replace 1's and 0's in a gridview column with Yes's and No's
Is it possible to change the display of a column in a gridview to show a Yes for all 1's and a No for 0's that display in a particular column of a gridview bound to a database?  If so, can someone share the way with me?  I am using ASP.NET 2.0 with VB Code Behind.  Thanks One way you can do is thrrough  CASE in your select statement: Select YesNoColumn= CASE yourColumn WHEN 1 THEN 'Yes' WHEN 0 THEN 'No' ELSE '' END FROM YourtableLimno <Columns>     <asp:TemplateField HeaderText="yourHeader" SortExpression="yourDataField"> ...

GridView doesn't refresh it's schema after the object data source's GetData() method returns additional fields .
Hi . I am creating an ASP.NET web site and have the following problem :  I have a GridView which bound to the object data source. This object data source is SQL Table adapter that I added to the data set via IDE . The method GetData of this table adapter uses existing stored procedure on my SQL 2005 server. Everything worked fine , until I made a changes to the stored procedure ( the new result records have additional fields )  .  The problem is :   The new fields don’t appear in the grid . Note : When I right click to the GetData method inside the tabl...

What's wrong with DataBind() in GridView control? The data in GridView can't be updated when the datasource have changed!
What's wrong with DataBind() in GridView control? The data in GridView can't be updated when the datasource have changed! I bind the different datasource to the Gridview when I change the node of TreeView, the GridView control always display the same data when I click different the node of TreeView control,why?but I can get the different data in GridView when I click the Button1 or Button2. //-------------------Program Code (You may save it as a ASPX file and run it)--------------------------------<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http:/...

First gridview's selected row doesn't update second gridview's objectdatasource
 HelloI got 2 gridviews on a page, each with its own ObjectDataSource. The first gridview fills itself just normally, no problem there. The second gridview needs to fill itself with other data, where the primary key is the primary key of the selected row of the first gridview.schematically:gridview1 row: IDfield, x, y, zrow: IDfield, x, y, z (-> this row is selected)row: IDfield, x, y, z gridview2 row:IDfield_of_selected_row_in_gridview1, a, b, c I tried to do this by configuring the ObjectDataSource behind gridview2 with a parameter pointing to gridview1.selectedValue. (by usin...

superreview requested: [Bug 344505] role="anything" on <table> should remove roleless <td>'s, <th's> from hierarchy : [Attachment 229522] Any role on a table means the table structure descendants are
Aaron Leventhal <aaronleventhal@moonset.net> has asked for superreview: Bug 344505: role="anything" on <table> should remove roleless <td>'s, <th's> from hierarchy https://bugzilla.mozilla.org/show_bug.cgi?id=344505 Attachment 229522: Any role on a table means the table structure descendants are no longer structurally relevant, unless they have their own role. They're being used to layout the container. https://bugzilla.mozilla.org/attachment.cgi?id=229522&action=edit ...

superreview cancelled: [Bug 344505] role="anything" on <table> should remove roleless <td>'s, <th's> from hierarchy : [Attachment 229522] Any role on a table means the table structure descendants are
Aaron Leventhal <aaronleventhal@moonset.net> has cancelled Aaron Leventhal <aaronleventhal@moonset.net>'s request for superreview: Bug 344505: role="anything" on <table> should remove roleless <td>'s, <th's> from hierarchy https://bugzilla.mozilla.org/show_bug.cgi?id=344505 Attachment 229522: Any role on a table means the table structure descendants are no longer structurally relevant, unless they have their own role. They're being used to layout the container. https://bugzilla.mozilla.org/attachment.cgi?id=229522&action=edi...

Why I can't bind a Datasource to an ImageButton's ImageURL Property?
Why I can't bind a CodeBehind method's return value to an ImageButton's ImageURL Property while a CSS Link can be work fine with the same method in the same Web Form? I have DataBind() method in my Page_Load subroutine the method in code behind is: Protected Function AppRootURL() As String Return ConfigurationSettings.AppSettings("AppRoot") End Function the Html code is: <LINK media=Screen href="<%# AppRootURL() %>/Skins/SkinA/SkinAStyle.css" type=text/css rel=StyleSheet> <asp:imagebutton id=ibnShowStartCa...

Generating a dynamic report, how to render <p>'s, <div>'s etc?
Hello, I'm writing a reporting application that takes information from an SQL database and presents it in a series of datagrids on several pages. I also need to generate a report in HTML based on some parameters. My first version used a Literal and simply wrote to that as if I was coding PHP or asp. So every line of HTML was 'hand crafted'. This gave me a lot of control but of course debugging was a bit of a bear (wrong nesting, forgotten closing tags etc.) So I rewrote the page to use a placeholder that I add controls to that I generate on the fly. Simple enough for tables and URLs. B...

Create a DIV's property that points other's object property...
Hi, I have a DIV object. I want to create a property type pointer, that points to a other's object property. For example: I want add a property SelectedIndex to a DIV object. This property must points to the property SelectedIndex of another combo object. In other words. I want that if the combo's property change its value, the property in the DIV object must be changed too. I want the same in the reverse direction. I don't want to use the onchange of the combo objet. I want that if we interact with the combo's property in script, the changes should be reflected in the DIV's...

Unable to access user control's user control's function\property from another user control
Hi, I used to call an user control's user control function as stated below from my user control in ASP.Net 1.1 wucCompany.wucEmployee.GetEmployeeSomething() After migrating to ASP.Net 2.0, I am unable to use any properties/functions(even the public ones) of the user control's User control's from another user control.  The way I have to do is create property\function in wucCompany which calls the wucEmployee's property\function and call the wucDepartment.GetEmployeeSomething().Since I need to do this change in too many places, I can...

Ajaxmodalpopup TextBox's --> TEXT--> GridView's TextBox
  Hi I have A Problem With my javascript,   ERROR: 'txtbox1' is undefine in javascript What i want to achieve: I have 1 textbox in my Gridview and i have Modalpopup, i want to transfer data from modalpopup to Gridview's Textbox like User will enter Text into modalpopup's Textbox and Text should go to Gridview's Textbox  for that i have below code:  CODE BEHIND:  For Each gvr As GridViewRow In GridView2.Rows 'Get a programmatic reference to the CheckBox control 'Dim cb As CheckBox = CType(gvr.FindControl("chkBox1"), Ch...

superreview granted: [Bug 397222] Bogus 'for' attributes shadowing 'control ' attributes on <label>s
neil@parkwaycc.co.uk <neil@httl.net> has granted Phil Ringnalda <philringnalda@gmail.com>'s request for superreview: Bug 397222: Bogus 'for' attributes shadowing 'control' attributes on <label>s https://bugzilla.mozilla.org/show_bug.cgi?id=397222 Attachment 281988: Fix v.1 https://bugzilla.mozilla.org/attachment.cgi?id=281988&action=edit ...

superreview requested: [Bug 397222] Bogus 'for' attributes shadowing ' control' attributes on <label>s
Phil Ringnalda <philringnalda@gmail.com> has asked neil@parkwaycc.co.uk <neil@httl.net> for superreview: Bug 397222: Bogus 'for' attributes shadowing 'control' attributes on <label>s https://bugzilla.mozilla.org/show_bug.cgi?id=397222 Attachment 281988: Fix v.1 https://bugzilla.mozilla.org/attachment.cgi?id=281988&action=edit ------- Additional Comments from Phil Ringnalda <philringnalda@gmail.com> These appear to be the only ones that aren't included in bug 397097 (which is already having to reach pretty far outside its remit, withou...

Web resources about - How to bind GridView's DataSource to an object's List<T> property?? - asp.net.presentation-controls

Resources last updated: 12/3/2015 12:06:43 PM